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.
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.
- Navigate to Error Logs → Settings in the WordPress admin sidebar.
- Click the “Snippets Options” tab (or scroll to the section headed Snippets options).
- Toggle the “Enable Snippets module” checkbox.
- Click Save Changes.
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 |
|
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
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. |
Dropdown Filters
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.
Searching Snippets
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
- On the Snippet list page, click “Add New” (top-right, next to the page title).
- Enter a Name for the snippet (required).
- Write or paste your PHP code in the Code editor (required). Do not include opening
<?phptags — the sandbox handles this automatically. - 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).
- Click Save Snippet.
Editing a Snippet
Click Edit on any row to open the editor form.
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.
<?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:
- Make sure the snippet is Enabled and its type is PHP.
- From the snippet list, hover over the row and click Execute. Alternatively, open the Edit form and click Execute snippet in the sidebar.
- 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.
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.,
1runs before10). - 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().
- Open (or create) a snippet.
- In the sidebar, enter a tag in the Shortcode tag field (e.g.,
my_snippet). - Save the snippet and ensure it is Enabled.
- In any post or page, use
[my_snippet]to execute the snippet and render its output.
$atts (shortcode attributes), $content (enclosed content), and $shortcode (the tag name).Example: Inline Shortcode
In your post content:
[my_snippet]In your snippet code:
<?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:
[my_greeting name="Alice" greeting="Hello"]In your snippet code:
<?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=frontendRun only on WooCommerce product pages
post_type=productRun during AJAX or WP-CLI requests (pipe for alternatives)
request=ajax|cliRun for admins OR on the front-end (OR logic with ||)
cap=manage_options || request=frontendRun only on URLs under /shop/
url_path=/shop/*JSON format (advanced)
[
{ "field": "user_role", "operator": "eq", "values": ["editor"] },
{ "field": "request", "operator": "eq", "values": ["frontend"] }
]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:
- Check the boxes next to the snippets you want to act on. Use the checkbox in the header row to select all visible snippets.
- Open the Bulk actions dropdown (top-left or bottom-left of the table).
- 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:
- Apply any desired filters or search (the export respects your current filter context).
- Click the “CSV Export” button above the table.
- A progress bar appears during the export. You can click Cancel if needed.
- 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:
- 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.
- Delete Permanently — Switch to the Trash view and click “Delete Permanently”. This removes the snippet from the database entirely.
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 |
See
Snippets Module Developer Documentation for architectural details, class references, sandbox internals, condition evaluator API, and code examples for extending the Snippets module programmatically.