Snippets Module — User Guide

Table of Contents

The Snippets Module is a full code-snippet manager built into Advanced Analytics. It allows WordPress administrators to create, manage, and execute reusable PHP code snippets directly from the admin area — with advanced execution controls, conditional logic, shortcode registration, and a sandboxed runtime environment.

Who is this for?
You need the Administrator role (the manage_options capability) to access the Snippets module. Other user roles will not see the menu item.

Enable / Disable the Module

The Snippets module is a standalone module inside Advanced Analytics. You can enable or disable it without affecting any other part of the plugin or WordPress itself.

  1. Navigate to Error Logs → Settings in the WordPress admin sidebar.
  2. Click the “Snippets Options” tab (or scroll to the section headed Snippets options).
  3. Toggle the “Enable Snippets module” checkbox.
  4. Click Save Changes.
wp-admin/admin.php?page=advan_logs_settings#aadvana-options-tab-snippets
Important: Disabling the module hides the Snippets sub-menu from the admin and stops all snippet execution. Enabled snippets will not run while the module is disabled. Re-enabling the module restores all previously enabled snippets to active execution.

Module Settings

The Snippets Options tab on the Settings page has two settings:

1. Enable Snippets module

Type Checkbox
Default Enabled (checked)
Effect Shows or hides the Snippets sub-menu and all associated functionality. When disabled, no snippets are executed — neither via hooks nor via shortcodes.

2. Sandbox storage location

Type Radio (two options)
Default uploads
Options
  • Dedicated folder inside uploads/ (uploads) — Uses a folder at wp-content/uploads/advanced-analytics/snippets-runtime/ to store temporary execution files.
  • php://temp memory stream (php_temp) — Executes snippet code entirely in memory without touching the filesystem.
When to choose which? Use the uploads option (default) when your server’s /tmp directory is unavailable or restricted. Switch to php_temp if you prefer to avoid writing any temporary files to disk. Both options are secure and sandboxed.

Snippet List

wp-admin/admin.php?page=advan_snippets

This is the main screen. It shows every snippet stored on your site in a sortable, filterable table.

Columns

Column Sortable Description
Name Yes The display name of the snippet. Row actions appear on hover beneath the name.
Type Yes The snippet language: PHP or WP-CLI.
Status Yes Shows Enabled, Disabled, or Trashed with colour-coded labels.
Scope Yes Where the snippet runs: Everywhere, Admin area, Front-end, or Manual execution.
Hook Yes The WordPress action hook the snippet attaches to (e.g., init).
Priority Yes The hook execution priority. Lower numbers run earlier. Default is 10.
Shortcode Yes If a shortcode tag is assigned, it shows [tag]. Otherwise a dash.
Tags No Comma-separated labels for organizing snippets.
Last Run Yes Timestamp of the most recent execution, shown as a relative time (e.g., “5 min ago”).
Last Result Yes Outcome of the most recent execution: success, error, skipped, or never.
Updated Yes When the snippet was last modified.
Site ID Yes Multisite only. The blog ID of the site owning the snippet.

Filters & Views

Status Views

Above the table you will find quick-filter links. Each shows a count in parentheses:

View Shows
All All non-trashed snippets (enabled + disabled).
Enabled Only snippets with status Enabled.
Disabled Only snippets with status Disabled.
Trash Snippets that have been moved to the trash.

Use the dropdown menus above the table then click Filter:

Status Filter

  • Default: “All statuses”
  • Options: Enabled, Disabled, Trash.
  • Narrows the table to only snippets matching the selected status.

Type Filter

  • Default: “All types”
  • Options: PHP, WP-CLI.
  • Narrows the table to only snippets of the selected type.

Use the search box in the top-right corner of the list page. It searches by snippet name and tags.

  • Type part of a name or tag and press Enter or click Search snippets.
  • The search is case-insensitive and matches partial text.
  • To clear the search, empty the box and press Enter.

Single Snippet Actions

Hover over any snippet row to reveal these actions below the snippet name:

Non-Trashed Snippets

Action Description
Enable / Disable Toggle the snippet’s active status. Enabled snippets run automatically on their assigned hook.
Edit Opens the snippet editor form with all values pre-filled.
Execute Runs the snippet immediately in the sandbox (PHP snippets only). The snippet must be enabled first.
Duplicate Creates a copy of the snippet. The clone is saved as Disabled with a unique name and slug.
Move to Trash Soft-deletes the snippet. It can be restored later from the Trash view.

Trashed Snippets

Action Description
Restore Moves the snippet out of trash back to disabled status.
Delete Permanently Removes the snippet from the database. This cannot be undone.

Adding a New Snippet

  1. On the Snippet list page, click “Add New” (top-right, next to the page title).
  2. Enter a Name for the snippet (required).
  3. Write or paste your PHP code in the Code editor (required). Do not include opening <?php tags — the sandbox handles this automatically.
  4. Configure the sidebar options:
    • Execution type — Choose PHP or WP-CLI.
    • Status — Check the box to enable the snippet immediately.
    • Tags — Optional comma-separated labels.
    • Execution scope — Where the snippet should run (see Execution Scopes).
    • Hook name — The WordPress action to attach to (default: init).
    • Hook priority — Execution order on the hook (default: 10).
    • Shortcode tag — Optional. Register a [shortcode] for this snippet.
    • Run conditions — Optional conditional logic rules (see Run Conditions).
  5. Click Save Snippet.
Auto-generated slug: A URL-safe slug is automatically created from the snippet name. It is unique per site and appears in the Snapshot panel after saving.

Editing a Snippet

Click Edit on any row to open the editor form.

wp-admin/admin.php?page=advan_snippets&action=edit&snippet={id}

Form Fields

Field Type Required Description
Name Text input Yes Display name for the snippet (max 190 characters).
Code Textarea (CodeMirror editor) Yes The PHP code to execute. Runs inside a sandboxed closure.
Execution type Select dropdown No Choose PHP or WP-CLI.
Status Checkbox No Checked = Enabled. Unchecked = Disabled.
Tags Text input No Comma-separated helper labels (max 12 tags).
Execution scope Select dropdown No Everywhere, Admin area, Front-end, or Manual execution.
Hook name Text input No WordPress action hook to attach to. Default: init.
Hook priority Number input No Priority on the hook (min 1). Default: 10.
Shortcode tag Text input No Register a [tag] for this snippet. Must be unique per site (max 60 characters).
Run conditions Textarea No Conditional execution rules. Comma or newline separated.

Snapshot Panel

The sidebar also displays a read-only Snapshot section showing:

  • Slug — The auto-generated unique identifier.
  • Scope — Current execution scope.
  • Last run — When the snippet last executed (relative time).
  • Last result — Outcome of the last execution.
  • Created — Creation date/time in your site’s local timezone.
  • Updated — Last modification date/time.
  • Shortcode — The registered shortcode tag, or a dash if none.

The Code Editor

The snippet editor uses CodeMirror with the Cobalt theme for PHP syntax highlighting, auto-indentation, and line numbers.

Editor Features

  • PHP syntax highlighting
  • Auto-indentation (4 spaces per level)
  • Line numbers in the gutter
  • Bracket matching
  • Scrollable for long snippets

Resizable Sidebar

The editor workspace is divided into two panels: the code editor (left) and the settings sidebar (right). You can:

  • Resize — Drag the vertical divider between the two panels.
  • Collapse / Expand — Click the sidebar toggle button to hide or show the sidebar entirely.
  • Your sidebar state is saved in your browser’s local storage and persisted across page loads.
No opening PHP tag needed: Do not start your snippet with <?php. The sandbox automatically wraps your code in a proper PHP closure. Including the tag may cause a parse error.

Executing Snippets

Automatic Execution (Hooks)

When a snippet is Enabled, it runs automatically on every matching WordPress request. The snippet is attached to the configured hook (default: init) with the specified priority. The execution scope and run conditions determine whether it actually fires on a given request.

Manual Execution

You can execute a snippet on demand from the admin:

  1. Make sure the snippet is Enabled and its type is PHP.
  2. From the snippet list, hover over the row and click Execute. Alternatively, open the Edit form and click Execute snippet in the sidebar.
  3. The snippet runs immediately in the sandbox. A result notice appears showing:
    • Status — success or error.
    • Message — Any error message or informational output.
    • Output — Captured STDOUT (limited to 15 KB).
    • Result — The return value of the snippet code.
Tip: Use the clipboard icon to copy the execution result, or the share icon (on supported devices) to share it via the native share API.

Shortcode Execution

If you assign a shortcode tag to a snippet, the snippet runs wherever you place [your_tag] in post content, widgets, or templates. See the Shortcode Registration section for details.

Execution Scopes

The execution scope controls where the snippet runs automatically when enabled:

Scope Runs In Use Case
Everywhere Admin area + front-end + AJAX + REST + CLI General-purpose snippets that should apply to all contexts.
Admin area WordPress admin pages only (is_admin()) Snippets that modify the admin UI, add admin notices, or tweak settings.
Front-end Public-facing pages only Snippets that add custom output, modify templates, or inject scripts.
Manual execution Only when manually executed or via shortcode Utility snippets you want to run on demand without automatic hook attachment.

Hooks & Priority

Each snippet attaches to a WordPress action hook. When that hook fires, the snippet executes.

Hook Name

Enter any valid WordPress action hook name. Common choices:

  • init — Fires after WordPress is fully set up (default).
  • wp_loaded — Fires after all plugins and themes are loaded.
  • admin_init — Fires on every admin page load.
  • wp_head — Fires in the <head> section of front-end pages.
  • wp_footer — Fires before the closing </body> tag.
  • template_redirect — Fires before a template file loads.

Hook Priority

Controls the order of execution when multiple callbacks are registered on the same hook:

  • Lower numbers run earlier (e.g., 1 runs before 10).
  • Default is 10 (same as WordPress default).
  • Use lower priority to run before other plugins; higher priority to run after.

Shortcode Registration

Assigning a shortcode tag to a snippet allows you to embed the snippet’s output anywhere WordPress processes shortcodes — posts, pages, widgets, and templates via do_shortcode().

  1. Open (or create) a snippet.
  2. In the sidebar, enter a tag in the Shortcode tag field (e.g., my_snippet).
  3. Save the snippet and ensure it is Enabled.
  4. In any post or page, use [my_snippet] to execute the snippet and render its output.
Shortcode context variables: When triggered via shortcode, your snippet code has access to $atts (shortcode attributes), $content (enclosed content), and $shortcode (the tag name).
Uniqueness: Shortcode tags must be unique per site. If another snippet (or plugin) already uses the same tag, you will see an error: “Shortcode already belongs to another snippet.”

Example: Inline Shortcode

In your post content:

JSON
[my_snippet]

In your snippet code:

PHP
<?php
// This snippet outputs the current server time.
return 'Server time: ' . gmdate( 'Y-m-d H:i:s' ) . '
';

Example: Shortcode with Attributes

In your post content:

JSON
[my_greeting name="Alice" greeting="Hello"]

In your snippet code:

PHP
<?php
$name = isset( $atts['name'] ) ? sanitize_text_field( $atts['name'] ) : 'World';
$greeting = isset( $atts['greeting'] ) ? sanitize_text_field( $atts['greeting'] ) : 'Hi';
return "{$greeting}, {$name}!
";

Run Conditions

Run conditions let you restrict when a snippet executes even if it is enabled and the hook fires. Conditions are evaluated on every request; if they do not pass, the snippet is silently skipped.

Syntax

Enter conditions in the Run conditions textarea. Rules can be written as:

  • Comma or newline separated — all rules in a group must pass (AND logic).
  • Double-pipe || separated — any group can pass (OR logic).
  • Pipe | inside a value — match any of the listed values.
  • JSON array format — for advanced structured rules.

Supported Rule Keys

Key Aliases Accepted Values Example
role user_role Any WordPress role name role=administrator
cap user_capability Any WordPress capability cap=manage_options
request context admin, frontend, ajax, cron, rest, cli request=frontend
trigger hook, shortcode, manual trigger=manual
hook Hook name (supports * wildcard) hook=init_*
shortcode Shortcode tag name shortcode=my_snippet
post_type Any post type slug post_type=product
url_path path URL path (supports * wildcard) url_path=/shop/*
request_param param GET/POST key=value param.search=shoes
query_var WP_Query variable query_var.post_type=page

Operators

Operator Aliases Meaning
= ==, eq Equal
!= neq Not equal
> gt Greater than (numeric/datetime)
>= gte Greater than or equal
< lt Less than (numeric/datetime)
<= lte Less than or equal

Examples

Run only for editors on the front-end (AND logic)

user_role=editor, request=frontend

Run only on WooCommerce product pages

post_type=product

Run during AJAX or WP-CLI requests (pipe for alternatives)

request=ajax|cli

Run for admins OR on the front-end (OR logic with ||)

Shell
cap=manage_options || request=frontend

Run only on URLs under /shop/

JavaScript
url_path=/shop/*

JSON format (advanced)

JSON
[
    { "field": "user_role", "operator": "eq", "values": ["editor"] },
    { "field": "request", "operator": "eq", "values": ["frontend"] }
]
Preview: After saving, the edit form displays a Parsed rules preview beneath the conditions textarea, showing how your rules were interpreted.

Tags

Tags are comma-separated labels that help you organize and find snippets. They serve as a descriptive categorization mechanism.

  • Enter tags as comma-separated values, e.g.: wp, cleanup, utility.
  • Maximum of 12 tags per snippet — additional tags are silently trimmed.
  • Duplicate tags are automatically removed.
  • Tags are included in search results — searching for a tag name will show matching snippets.

Bulk Actions

Perform operations on multiple snippets at once:

  1. Check the boxes next to the snippets you want to act on. Use the checkbox in the header row to select all visible snippets.
  2. Open the Bulk actions dropdown (top-left or bottom-left of the table).
  3. Choose an action and click Apply.

Available Bulk Actions (Non-Trash View)

Action Description
Enable Enable all selected snippets (they will start running automatically).
Disable Disable all selected snippets (they stop running but remain in the list).
Move to Trash Soft-delete all selected snippets.

Available Bulk Actions (Trash View)

Action Description
Restore Move all selected snippets out of the trash.
Delete Permanently Remove all selected snippets from the database permanently.

CSV Export

Export the currently filtered/displayed snippets to a CSV file:

  1. Apply any desired filters or search (the export respects your current filter context).
  2. Click the “CSV Export” button above the table.
  3. A progress bar appears during the export. You can click Cancel if needed.
  4. The CSV file downloads automatically once complete.

Trash & Permanent Delete

The Snippets module uses a two-step deletion process to protect against accidental data loss:

  1. Move to Trash — Click “Move to Trash” on any snippet. The snippet stops executing and moves to the Trash view. It can be restored at any time.
  2. Delete Permanently — Switch to the Trash view and click “Delete Permanently”. This removes the snippet from the database entirely.
Warning: Permanent deletion cannot be undone. The snippet code and all associated metadata (execution history, conditions, shortcode registration) are lost.
Safety: You can only permanently delete a snippet that is already in the trash. Attempting to delete a non-trashed snippet directly will show an error.

Screen Options

Click Screen Options (top-right of the page, just below the admin bar) to customize the display:

Items per page

Control how many snippets display per page. Enter a number and click Apply. Default is 20. This only affects your user account.

Column Visibility

Check or uncheck columns to show or hide them. Useful for reducing clutter when you don’t need certain information (e.g., hiding the Priority or Hook columns). Settings persist across sessions.

Multisite Networks

On WordPress multisite installations, the Snippets module provides site-level isolation:

  • Site ID column — Each snippet row shows which site (blog ID) it belongs to.
  • Per-site scoping — Snippets are scoped to the blog where they were created. A snippet on Site A cannot be viewed or edited from Site B.
  • Unique slugs per site — Two different sites can have snippets with the same name without conflicts.
  • Unique shortcodes per site — Shortcode tags only need to be unique within a single site.

Troubleshooting

“Name and code are required.”

You submitted the form with an empty name or empty code field. Both are mandatory. Enter a descriptive name and at least one line of code.

“Shortcode already belongs to another snippet.”

The shortcode tag you entered is already in use by a different snippet on the same site. Choose a unique tag, or remove the tag from the other snippet first.

“Unable to parse run conditions.”

The conditions you entered could not be parsed. Check the syntax against the supported rule keys. Common issues:

  • Missing = sign between key and value.
  • Using unsupported field names.
  • Malformed JSON (if using JSON format).

“Enable the snippet before executing it.”

You tried to manually execute a snippet that is currently disabled. Edit the snippet and check the Enabled checkbox first, or use the Enable row action from the list.

“Only PHP snippets can be executed from here.”

The manual execute action is only available for PHP-type snippets. WP-CLI snippets cannot be run from the admin interface.

“Snippet does not belong to this site.”

On multisite, you tried to access a snippet that belongs to a different site. Navigate to the correct site’s admin area to manage that snippet.

Snippet runs but produces no output

The snippet may have executed successfully without any visible side effects. Check:

  • Is the snippet running on the correct hook and scope?
  • Do the run conditions match the current context?
  • If using a shortcode, is the snippet enabled and does the shortcode tag appear in the content?
  • Check the Last Result column — if it shows “skipped”, the conditions were not met.

Snippet causes a white screen or error

If a snippet introduces a fatal error, it may disrupt the page it runs on. To recover:

  • Navigate to the snippets list (the list view itself does not execute snippet code).
  • Disable the problematic snippet using the Disable row action.
  • If the admin is completely inaccessible, disable the snippets module by updating the plugin settings in the database (option: snippets_module_enabled).

Error Messages Reference

Message Cause Solution
“Name and code are required.” Empty name or code field Fill in both fields
“Shortcode already belongs to another snippet.” Duplicate shortcode tag Use a unique shortcode tag
“Unable to parse run conditions.” Invalid condition syntax Check syntax against the supported rule keys
“Snippet not found.” Snippet ID does not exist Return to the list and refresh
“Cannot toggle a trashed snippet.” Tried to enable/disable from trash Restore the snippet first, then toggle status
“Move the snippet to trash before deleting permanently.” Tried to permanently delete a non-trashed snippet Move to trash first, then delete permanently
“Insufficient permissions.” Non-administrator user Log in as an administrator with manage_options capability
“Please add code before saving.” JavaScript validation — empty code editor Add code to the editor before clicking Save
Need developer documentation?
See Snippets Module Developer Documentation for architectural details, class references, sandbox internals, condition evaluator API, and code examples for extending the Snippets module programmatically.
← 0 Day Analytics – Snippets Module Developer Documentation Common WordPress Security Advices That Are Actually Useless →
Share this page
Back to top