Table of Contents
1. Overview & Architecture
The Snippets Module provides a complete PHP code snippets management system within the WordPress
admin. It allows administrators to create, edit, execute, and manage custom PHP code snippets that can run on
various WordPress hooks, as shortcodes, or be executed manually.
Key Capabilities
Create and manage PHP code snippets with a CodeMirror-powered editor
Execute snippets on any WordPress hook with configurable priority
Register snippets as shortcodes for use in content
Define conditional execution rules based on user roles, capabilities, request context, and more
Execute snippets manually from the admin interface
Track execution history with status and output logging
Duplicate, enable, disable, and trash snippets
Sandbox execution environment with output capture and error handling
Multisite support with blog-scoped snippets
Technology Stack
PHP 7.4+ (strict types)
WordPress WP_List_Table API
CodeMirror editor integration via wp_enqueue_code_editor()
Custom database table for snippet storage
Sandbox execution via temporary files or php://temp streams
2. File Map
advanced-analytics/
├── classes/
│ └── vendor/
│ ├── entities/
│ │ └── class-snippet-entity.php — Database entity & CRUD operations
│ ├── helpers/
│ │ ├── class-snippets-sandbox.php — Code execution sandbox
│ │ └── class-snippet-condition-evaluator.php — Run conditions parser
│ ├── controllers/
│ │ └── classes-snippets-controller.php — Runtime hook/shortcode registration
│ ├── lists/
│ │ ├── class-snippets-list.php — WP_List_Table for snippets
│ │ └── views/
│ │ └── class-snippets-view.php — Page rendering & form handlers
│ └── settings/
│ └── settings-options/
│ └── snippets.php — Module settings fields
└── assets/
├── css/
│ └── snippets-editor.css — Form & workspace styling
└── js/
└── snippets-editor.js — Sidebar toggle & form validation
3. Admin Screens
3.1 Snippets List
URL
wp-admin/admin.php?page=advan_snippets
Menu Position
Sub-menu under “Error Logs” (position 6)
Capability
manage_options
Controller
Snippets_View::render_page()
List Table
Snippets_List (extends WP_List_Table)
UI Components
“Add New Snippet” button in page header
Filter views – All | Enabled | Disabled | Trash
Search box – searches name and tags
Type filter dropdown – PHP or WP-CLI
Status filter dropdown – All statuses, Enabled, Disabled
Sortable columns – Name, Type, Status, Scope, Hook, Priority, Last Run, Updated
Row actions – Toggle | Edit | Execute | Duplicate | Move to Trash
Bulk actions – Enable | Disable | Move to Trash (or Restore | Delete Permanently for
trashed)
Screen layout:
┌──────────────────────────────────────────────────────────────┐
│ Snippets [Add New Snippet] │
│──────────────────────────────────────────────────────────────│
│ All (12) | Enabled (8) | Disabled (3) | Trash (1) │
│ [Type ▼] [Status ▼] [Filter] [🔍 Search] │
│──────────────────────────────────────────────────────────────│
│ ☐ Name ↕ | Type | Status | Scope | Hook | Priority │
│ ☐ My Snippet | PHP | Enabled | Frontend | init | 10 │
│ Enable | Edit | Execute | Duplicate | Trash │
│ ☐ Another | PHP | Disabled| Admin | admin_init | 20 │
│ Disable | Edit | Execute | Duplicate | Trash │
│──────────────────────────────────────────────────────────────│
│ Bulk Actions [▼] [Apply] ‹ 1 of 2 › │
└──────────────────────────────────────────────────────────────┘
3.2 Edit Snippet
URL
wp-admin/admin.php?page=advan_snippets&action=edit&snippet={id}
Form Action
admin_post_advan_snippet_save
Handler
Snippets_View::handle_save()
Nonce
advan_manage_snippets
Field
Type
Name
Description
Snippet ID
hidden
snippet_id
The snippet database ID
Name
text
snippet_name
Snippet display name (required)
Type
select
snippet_type
php or wp_cli
Status
checkbox
snippet_status
Enabled when checked
Tags
text
snippet_tags
Comma-separated, max 12 tags
Code
textarea
snippet_code
PHP code (CodeMirror enhanced)
Scope
select
snippet_scope
global, admin, frontend, or manual
Hook
text
snippet_hook
WordPress action hook (default: init)
Priority
number
snippet_priority
Hook priority (default: 10)
Shortcode
text
snippet_shortcode
Optional shortcode tag (unique per blog)
Run Conditions
textarea
snippet_conditions
Conditional execution rules
Note: The code editor uses CodeMirror with the “cobalt” theme. The field ID for
JavaScript targeting is snippet-code.
3.3 Add New Snippet
URL
wp-admin/admin.php?page=advan_snippets&action=add
Form Action
admin_post_advan_snippet_save
Handler
Snippets_View::handle_save()
Nonce
advan_manage_snippets
Uses the same form fields as Edit. On save, a unique slug is auto-generated from the name.
3.4 Module Settings
URL
wp-admin/admin.php?page=advan_logs_settings#aadvana-options-tab-snippets
Settings File
classes/vendor/settings/settings-options/snippets.php
Available Settings
Setting
ID
Type
Description
Enable Snippets module
snippets_module_enabled
checkbox
Enables/disables the entire Snippets module. When disabled, snippets will not execute and the UI
is hidden.
Sandbox storage location
snippets_temp_storage
radio
Choose between uploads (dedicated folder in wp-content/uploads/) or
php_temp (php://temp memory stream).
Use php_temp when the filesystem is restricted or /tmp is unavailable. Use
uploads for better debugging capabilities with temporary files.
4. Core Classes
4.1 ADVAN\Entities\Snippet_Entity
Database entity class handling all snippet CRUD operations. Extends Abstract_Entity.
Constants
<?php
public const STATUS_TRASHED = -1 ;
public const STATUS_DISABLED = 0 ;
public const STATUS_ENABLED = 1 ;
public const SCOPE_EVERYWHERE = 'global' ;
public const SCOPE_ADMIN = 'admin' ;
public const SCOPE_FRONTEND = 'frontend' ;
public const SCOPE_MANUAL = 'manual' ;
private const DEFAULT_HOOK = 'init' ;
private const DEFAULT_PRIORITY = 10 ;
private const SUPPORTED_TYPES = array ( 'php' => 'PHP' , 'wp_cli' => 'WP-CLI' );
Static Methods
Method
Return
Description
create_table($connection)
bool
Creates the snippets database table
get_snippet(int $id)
array
Load single snippet by ID
get_by_slug(string $slug, ?int $blog_id)
array
Load snippet by unique slug
get_by_shortcode(string $tag, ?int $blog_id)
array
Load snippet by shortcode tag
get_runtime_snippets()
array
Get all enabled PHP snippets for current blog
get_snippets_with_filters(array $filters, int $offset, int $limit)
array
Query snippets with search/status/type filters
get_snippets_count_with_filters(array $filters)
int
Count snippets matching filters
get_execution_scopes()
array
Return scope options (global, admin, frontend, manual)
get_supported_types()
array
Return type options (php, wp_cli)
get_status_counters()
array
Count snippets by status for filter views
get_column_names_admin()
array
Column definitions for list table
CRUD Operations
Method
Description
insert(array $data)
Insert or update snippet (inherited from Abstract_Entity)
delete_by_id(int $id)
Permanently delete snippet
trash_by_id(int $id)
Move snippet to trash (status = -1)
restore_by_id(int $id)
Restore from trash (status = 0)
enable_by_id(int $id)
Set status to enabled (1)
disable_by_id(int $id)
Set status to disabled (0)
duplicate(int $id)
Clone snippet as disabled draft
store_execution_result(int $id, string $status, string $message, ?string $timestamp)
Log execution result
Sanitization Helpers
Method
Description
sanitize_tags(string $raw)
Parse comma-separated tags, unique, max 12
sanitize_hook_name(string $raw)
Lowercase, alphanumeric + underscore/dot/colon/hyphen, max 180 chars
sanitize_shortcode_tag(string $raw)
Lowercase, alphanumeric + underscore/hyphen, max 60 chars, no pure numbers
build_unique_slug(string $name, ?int $exclude_id)
Generate unique slug per blog from name
build_unique_shortcode_tag(string $tag, ?int $exclude_id)
Ensure shortcode uniqueness per blog
4.2 ADVAN\Lists\Snippets_List
Extends WP_List_Table (via Abstract_List). Handles the snippets admin list table
rendering, column management, sorting, searching, and bulk operations.
Constants
<?php
public const PAGE_SLUG = '0-day_page_advan_snippets' ;
public const SCREEN_OPTIONS_SLUG = 'advanced_analytics_snippets_list' ;
public const SEARCH_INPUT = 's' ;
public const MENU_SLUG = 'advan_snippets' ;
public const NONCE_NAME = 'advan_manage_snippets' ;
public const SAVE_ACTION = 'advan_snippet_save' ;
public const DELETE_ACTION = 'advan_snippet_delete' ;
public const EXECUTE_ACTION = 'advan_snippet_execute' ;
public const TRASH_ACTION = 'advan_snippet_trash' ;
public const RESTORE_ACTION = 'advan_snippet_restore' ;
public const CLONE_ACTION = 'advan_snippet_clone' ;
public const TOGGLE_ACTION = 'advan_snippet_toggle' ;
private const BULK_FIELD = 'aadvana_snippet_ids' ;
Key Methods
Method
Description
init()
Registers all admin_post action handlers
menu_add()
Registers the admin submenu page under Error Logs
maybe_enqueue_code_editor(string $hook_suffix)
Loads CodeMirror for add/edit screens
process_actions_load()
Processes bulk actions on page load
prepare_items()
Populates the table with filtered/sorted data
fetch_table_data(array $args)
Retrieves snippets from database with filters
get_views()
Returns status filter tabs (All, Enabled, Disabled, Trash)
get_bulk_actions()
Returns available bulk actions based on current view
handle_table_actions()
Executes selected bulk action
manage_columns($columns)
Defines visible table columns
column_name($item)
Renders name column with row actions
extra_tablenav($which)
Renders filter dropdowns above table
get_sortable_columns()
Returns sortable column definitions
Localized Script Data
The JavaScript object window.advanSnippetEditor is localized with:
<?php
array (
'emptyCodeMessage' => __ ( 'Please enter some code.' , '0-day-analytics' ),
'sidebarCollapsed' => __ ( 'Show options' , '0-day-analytics' ),
'sidebarExpanded' => __ ( 'Hide options' , '0-day-analytics' ),
'storageKey' => 'advanSnippetSidebarState' ,
)
4.3 ADVAN\Lists\Views\Snippets_View
Handles page rendering for all snippet screens (list, edit, add) and processes form submissions.
Public Static Methods
Method
Description
render_page()
Main page router – renders list or form based on action parameter
handle_save()
Handles add/edit form submission, validates and inserts snippet
handle_delete()
Permanently deletes snippet (from trash only)
handle_trash()
Moves snippet to trash
handle_restore()
Restores snippet from trash
handle_clone()
Duplicates snippet as disabled draft
handle_toggle()
Toggles snippet enabled/disabled status
handle_execute()
Executes PHP snippet in sandbox, stores result in transient
Execution Result Storage
When a snippet is executed manually, the result is stored in a transient:
<?php
$token = wp_generate_password ( 12 , false , false );
set_transient (
'advana_snippet_exec_' . $token ,
array (
'status' => 'success' ,
'message' => '' ,
'output' => '' ,
'result_dump' => '' ,
'duration' => 0.00123 ,
'snippet' => array (
'id' => 42 ,
'name' => 'My Snippet' ,
),
),
5 * MINUTE_IN_SECONDS
);
4.4 ADVAN\Controllers\Snippets_Controller
Bootstraps runtime snippet execution. Registers enabled snippets on their configured WordPress hooks and shortcodes.
Public Static Methods
Method
Description
init()
Called on plugin load; registers runtime hooks and shortcodes if module enabled
register_runtime_hooks()
Attaches enabled snippets to their configured WordPress action hooks
register_runtime_shortcodes()
Registers shortcode handlers for snippets with shortcode tags
Private Static Methods
Method
Description
get_runtime_snippets()
Cached getter for enabled PHP snippets
maybe_execute_runtime_snippet(array $snippet)
Executes snippet if scope and conditions allow
should_execute_in_context(array $snippet)
Checks execution scope (admin, frontend, global)
conditions_allow_execution(array $snippet, array $context)
Evaluates run conditions via Snippet_Condition_Evaluator
execute_runtime_snippet(array $snippet, array $context, bool $echo_output)
Executes snippet via sandbox and logs result
Execution Scope Logic
<?php
private static function should_execute_in_context ( array $snippet ): bool {
$scope = (string) ( $snippet ['execution_scope' ] ?? Snippet_Entity::SCOPE_EVERYWHERE );
switch ( $scope ) {
case Snippet_Entity::SCOPE_ADMIN:
return is_admin ();
case Snippet_Entity::SCOPE_FRONTEND:
return ! is_admin () || wp_doing_ajax ();
case Snippet_Entity::SCOPE_MANUAL:
return false ;
default :
return true ;
}
}
4.5 ADVAN\Helpers\Snippets_Sandbox
Safely executes PHP snippets in an isolated sandbox environment with output capture and error handling.
Constants
<?php
private const OUTPUT_LIMIT = 15000 ;
private const STORAGE_UPLOADS = 'uploads' ;
private const STORAGE_STREAM = 'php_temp' ;
Public Static Methods
Method
Return
Description
execute(string $code, array $context)
array
Admin execution with manage_options capability check
execute_runtime(string $code, array $context)
array
Runtime execution without permission check
Return Structure
<?php
array (
'status' => 'success' ,
'message' => '' ,
'output' => '' ,
'duration' => 0.00123 ,
'result_dump' => '' ,
)
Prepared Context Variables
The following variables are automatically available inside snippet code via extract():
<?php
$defaults = array (
'wpdb' => $wpdb ,
'current_user' => wp_get_current_user (),
'site_url' => site_url (),
'home_url' => home_url (),
'blog_id' => get_current_blog_id (),
'is_multisite' => is_multisite (),
);
Code Wrapper
Snippet code is wrapped in a closure for isolation:
<?php
$wrapper = "return ( static function( array \$context ) {
extract( \$context, EXTR_SKIP );
" . $code . "
} );" ;
4.6 ADVAN\Helpers\Snippet_Condition_Evaluator
Parses and evaluates conditional execution rules for snippets.
Public Static Methods
Method
Return
Description
evaluate(?string $raw, array $context)
bool
Main evaluation method – returns true if conditions pass
get_normalized_rules(string $raw)
array
Normalizes conditions for UI preview
is_valid(string $raw)
bool
Quick validation helper
Supported Condition Fields
Field
Aliases
Example Values
role
user_role
administrator, editor, subscriber
cap
user_capability
manage_options, edit_posts
request
context
admin, frontend, ajax, cron,
rest, cli
trigger
—
hook, shortcode
hook
—
init, save_post, wp_footer (supports * wildcards)
shortcode
—
The shortcode tag name
post_type
—
post, page, product
url_path
path
/shop/*, /my-page (supports * wildcards)
request_param
param
key=value pairs from $_REQUEST
query_var
—
post_type=product
context.*
—
Access raw context values: context.trigger, context.hook
Supported Operators
Operator
Aliases
Description
eq
=, ==
Equals
neq
!=, ne
Not equals
gt
>
Greater than
gte
>=
Greater than or equal
lt
<
Less than
lte
<=
Less than or equal
# Comma or newline separated
role=administrator, request=admin
role=editor
request=frontend
# Multiple values with ||
role=administrator||editor, request=admin||ajax
# JSON array format
[{"field":"role","operator":"eq","values":["administrator"]}]
# Not equals
role != subscriber
request != cron
5. Data Model & Database Schema
Snippets are stored in a custom database table: {prefix}aadvana_snippets
Table Schema
CREATE TABLE `{prefix}aadvana_snippets` (
id bigint UNSIGNED NOT NULL AUTO_INCREMENT,
blog_id BIGINT UNSIGNED NOT NULL DEFAULT 0 ,
name VARCHAR (190 ) NOT NULL ,
slug VARCHAR (190 ) NOT NULL ,
type VARCHAR (40 ) NOT NULL DEFAULT "php" ,
status TINYINT (1 ) NOT NULL DEFAULT 0 ,
code LONGTEXT NOT NULL ,
tags VARCHAR (255 ) DEFAULT NULL ,
execution_scope VARCHAR (20 ) NOT NULL DEFAULT "global" ,
execution_hook VARCHAR (190 ) NOT NULL DEFAULT "init" ,
hook_priority INT NOT NULL DEFAULT 10 ,
shortcode_tag VARCHAR (100 ) DEFAULT NULL ,
run_conditions LONGTEXT NULL ,
last_run_at DATETIME NULL ,
last_run_status VARCHAR (40 ) NOT NULL DEFAULT "never" ,
last_run_message TEXT NULL ,
created_at DATETIME NOT NULL ,
updated_at DATETIME NOT NULL ,
PRIMARY KEY (id ),
KEY `idx_status` (status ),
KEY `idx_blog` (blog_id),
UNIQUE KEY `uniq_blog_slug` (blog_id, slug),
UNIQUE KEY `uniq_blog_shortcode` (blog_id, shortcode_tag)
);
Status Values
Value
Constant
Description
-1
STATUS_TRASHED
Snippet is in trash
0
STATUS_DISABLED
Snippet is disabled
1
STATUS_ENABLED
Snippet is enabled and will execute
Execution Scope Values
Value
Constant
Description
global
SCOPE_EVERYWHERE
Runs on both admin and frontend
admin
SCOPE_ADMIN
Runs only in admin area
frontend
SCOPE_FRONTEND
Runs only on frontend or AJAX
manual
SCOPE_MANUAL
Does not auto-run; manual execution only
Snippet Array Structure
<?php
$snippet = array (
'id' => 42 ,
'blog_id' => 1 ,
'name' => 'My Custom Snippet' ,
'slug' => 'my-custom-snippet' ,
'type' => 'php' ,
'status' => 1 ,
'code' => 'echo "Hello!";' ,
'tags' => 'utility, frontend' ,
'execution_scope' => 'frontend' ,
'execution_hook' => 'wp_footer' ,
'hook_priority' => 99 ,
'shortcode_tag' => 'my_snippet' ,
'run_conditions' => 'role=administrator' ,
'last_run_at' => '2026-03-25 10:30:00' ,
'last_run_status' => 'success' ,
'last_run_message' => '' ,
'created_at' => '2026-03-01 09:00:00' ,
'updated_at' => '2026-03-25 10:30:00' ,
);
6. Runtime Execution Flow
Hook-Based Execution
Snippets_Controller::init() is called during plugin initialization
If snippets_module_enabled setting is true, register_runtime_hooks() is called
All enabled PHP snippets are retrieved via Snippet_Entity::get_runtime_snippets()
For each snippet (except SCOPE_MANUAL), an action callback is added to the configured hook
When the hook fires, maybe_execute_runtime_snippet() checks scope and conditions
If allowed, Snippets_Sandbox::execute_runtime() runs the code
Execution result is logged via Snippet_Entity::store_execution_result()
Shortcode Execution
register_runtime_shortcodes() is called on the init hook (priority 25)
For each snippet with a non-empty shortcode_tag, a shortcode handler is registered
When the shortcode is processed, conditions are evaluated with trigger=’shortcode’ context
The snippet executes via sandbox with $atts, $content, and $shortcode
in context
Output is returned (not echoed) for shortcode content replacement
Manual Execution
Admin clicks “Execute” row action or submits execute form
Snippets_View::handle_execute() validates nonce and permissions
Snippet must be enabled and type must be ‘php’
Snippets_Sandbox::execute() runs with manage_options capability check
Result is stored in transient for display on redirect
Execution result is logged to the snippet’s last_run_* fields
7. Run Conditions System
Run conditions provide fine-grained control over when a snippet executes. Conditions are evaluated at runtime before
each execution.
Condition Syntax
Conditions can be written in multiple formats:
# Simple key=value pairs (comma or newline separated)
role=administrator
request=admin
# Multiple values (OR logic within a field)
role=administrator||editor
# Multiple conditions (AND logic between fields)
role=administrator, request=admin
# Not equals
role != subscriber
# Wildcards in hooks and paths
hook=woocommerce_*
url_path=/shop/*
# JSON format for complex conditions
[{"field":"role","operator":"eq","values":["administrator","editor"]}]
Evaluation Logic
Empty conditions = always execute
Conditions on the same line are ANDed together
Separate lines represent OR groups (any group passing = execute)
Multiple values in one field (using ||) are ORed
Context Variables in Shortcode Execution
When a snippet runs via shortcode, additional context is available:
<?php
$context = array (
'trigger' => 'shortcode' ,
'atts' => $atts ,
'content' => $content ,
'shortcode' => $tag ,
);
8. Hooks & Filters
Admin Post Actions ACTION
Action
Handler
Description
admin_post_advan_snippet_save
Snippets_View::handle_save
Save/update snippet
admin_post_advan_snippet_delete
Snippets_View::handle_delete
Permanently delete snippet
admin_post_advan_snippet_execute
Snippets_View::handle_execute
Execute snippet manually
admin_post_advan_snippet_trash
Snippets_View::handle_trash
Move snippet to trash
admin_post_advan_snippet_restore
Snippets_View::handle_restore
Restore snippet from trash
admin_post_advan_snippet_clone
Snippets_View::handle_clone
Duplicate snippet
admin_post_advan_snippet_toggle
Snippets_View::handle_toggle
Toggle snippet enabled/disabled
WordPress Hooks Used ACTION
Hook
Priority
Description
init
25
Registers shortcode handlers for enabled snippets
load-{page_slug}
—
Processes bulk actions early on page load
admin_enqueue_scripts
—
Enqueues CodeMirror on add/edit screens
Dynamic (per snippet)
Configurable
Each enabled snippet hooks into its configured action
9. Settings Reference
Settings are on the Snippets Options tab within the main settings page.
<?php
$enabled = Settings::get_option ( 'snippets_module_enabled' );
$storage = Settings::get_option ( 'snippets_temp_storage' );
Settings Builder Usage
<?php
Settings::build_option (
array (
'title' => esc_html__ ( 'Snippets Options' , '0-day-analytics' ),
'id' => 'snippets-options-settings-tab' ,
'type' => 'tab-title' ,
)
);
Settings::build_option (
array (
'name' => esc_html__ ( 'Enable Snippets module' , '0-day-analytics' ),
'id' => 'snippets_module_enabled' ,
'type' => 'checkbox' ,
'hint' => esc_html__ ( 'If you disable this, the Snippets module will be disabled...' , '0-day-analytics' ),
'toggle' => '#advana_snippets_settings-item' ,
'default' => Settings::get_option ( 'snippets_module_enabled' ),
)
);
Settings::build_option (
array (
'name' => esc_html__ ( 'Sandbox storage location' , '0-day-analytics' ),
'id' => 'snippets_temp_storage' ,
'type' => 'radio' ,
'default' => Settings::get_option ( 'snippets_temp_storage' ),
'options' => array (
'uploads' => esc_html__ ( 'Dedicated folder inside uploads/' , '0-day-analytics' ),
'php_temp' => esc_html__ ( 'php://temp memory stream' , '0-day-analytics' ),
),
)
);
10. List Table Columns & Sorting
Columns
Key
Header
Sortable
Description
cb
☐
No
Bulk selection checkbox
name
Name
Yes
Snippet name with row actions
type
Type
Yes
PHP or WP-CLI
status
Status
Yes
Enabled/Disabled badge
execution_scope
Scope
Yes
global, admin, frontend, or manual
execution_hook
Hook
Yes
WordPress action hook name
hook_priority
Priority
Yes
Hook priority number
shortcode_tag
Shortcode
Yes
Registered shortcode tag or —
tags
Tags
Yes
Comma-separated tags
last_run_at
Last Run
Yes
Timestamp of last execution
last_run_status
Last Result
Yes
success, error, or never
updated_at
Updated
Yes
Last modification timestamp
blog_id
Site ID
Yes
Multisite only – blog ID
Search
The search box filters by snippet name and tags. Query parameter: s
Filter Dropdowns
Type – All types, PHP, WP-CLI
Status – All statuses, Enabled, Disabled
Filter Views
All – All non-trashed snippets
Enabled – Snippets with status = 1
Disabled – Snippets with status = 0
Trash – Snippets with status = -1
11. Bulk & Row Actions
Row Actions (Active Snippets)
Action
Method
Description
Toggle
Page redirect
Toggles between enabled/disabled status
Edit
Page redirect
Opens the Edit Snippet form
Execute
Admin post
Runs the snippet immediately (PHP only)
Duplicate
Admin post
Creates a disabled copy of the snippet
Move to Trash
Admin post
Moves snippet to trash (status = -1)
Row Actions (Trashed Snippets)
Action
Method
Description
Restore
Admin post
Restores snippet to disabled status
Delete Permanently
Admin post
Permanently deletes snippet from database
Bulk Actions (Active View)
Action
Description
Enable
Enable all selected snippets
Disable
Disable all selected snippets
Move to Trash
Move all selected snippets to trash
Bulk Actions (Trash View)
Action
Description
Restore
Restore all selected snippets
Delete Permanently
Permanently delete all selected snippets
12. Code Examples
Example 1: Load a Snippet by ID
<?php
use ADVAN\Entities\Snippet_Entity;
$snippet = Snippet_Entity::get_snippet ( 42 );
if ( ! empty ( $snippet ) ) {
echo 'Snippet: ' . $snippet ['name' ];
echo 'Status: ' . ( Snippet_Entity::STATUS_ENABLED === (int) $snippet ['status' ] ? 'Enabled' : 'Disabled' );
}
Example 2: Execute a Snippet Programmatically
<?php
use ADVAN\Helpers\Snippets_Sandbox;
use ADVAN\Entities\Snippet_Entity;
$snippet = Snippet_Entity::get_snippet ( 42 );
if ( ! empty ( $snippet ) && 'php' === $snippet ['type' ] ) {
$result = Snippets_Sandbox::execute (
(string) $snippet ['code' ],
array (
'custom_var' => 'my_value' ,
)
);
if ( 'success' === $result ['status' ] ) {
echo 'Output: ' . $result ['output' ];
echo 'Duration: ' . $result ['duration' ] . 's' ;
} else {
echo 'Error: ' . $result ['message' ];
}
}
Example 3: Check Run Conditions
<?php
use ADVAN\Helpers\Snippet_Condition_Evaluator;
$conditions = 'role=administrator, request=admin' ;
$context = array (
'trigger' => 'hook' ,
'hook' => 'admin_init' ,
);
if ( Snippet_Condition_Evaluator::evaluate ( $conditions , $context ) ) {
echo 'Conditions passed!' ;
} else {
echo 'Conditions not met.' ;
}
Example 4: Query Snippets with Filters
<?php
use ADVAN\Entities\Snippet_Entity;
$filters = array (
'search' => 'woo' ,
'status' => 'enabled' ,
'type' => 'php' ,
);
$snippets = Snippet_Entity::get_snippets_with_filters ( $filters , 0 , 50 );
$count = Snippet_Entity::get_snippets_count_with_filters ( $filters );
foreach ( $snippets as $snippet ) {
printf (
"ID: %d | Name: %s | Hook: %s\n" ,
$snippet ['id' ],
$snippet ['name' ],
$snippet ['execution_hook' ]
);
}
Example 5: Create a Snippet Programmatically
<?php
use ADVAN\Entities\Snippet_Entity;
$now = gmdate ( 'Y-m-d H:i:s' );
$name = 'My Auto-Created Snippet' ;
$slug = Snippet_Entity::build_unique_slug ( $name );
$data = array (
'blog_id' => get_current_blog_id (),
'name' => $name ,
'slug' => $slug ,
'type' => 'php' ,
'status' => Snippet_Entity::STATUS_DISABLED,
'code' => 'echo "Hello from auto-generated snippet!";' ,
'tags' => 'auto, generated' ,
'execution_scope' => Snippet_Entity::SCOPE_FRONTEND,
'execution_hook' => 'wp_footer' ,
'hook_priority' => 99 ,
'shortcode_tag' => null ,
'run_conditions' => '' ,
'last_run_status' => 'never' ,
'last_run_message' => '' ,
'last_run_at' => null ,
'created_at' => $now ,
'updated_at' => $now ,
);
Snippet_Entity::insert ( $data );
Example 6: Validate Condition Syntax
<?php
use ADVAN\Helpers\Snippet_Condition_Evaluator;
$conditions = 'role=admin||editor, url_path=/products/*' ;
if ( Snippet_Condition_Evaluator::is_valid ( $conditions ) ) {
echo 'Conditions are valid!' ;
$rules = Snippet_Condition_Evaluator::get_normalized_rules ( $conditions );
print_r ( $rules );
} else {
echo 'Invalid condition syntax.' ;
}
Example 7: Get Snippet by Shortcode Tag
<?php
use ADVAN\Entities\Snippet_Entity;
$snippet = Snippet_Entity::get_by_shortcode ( 'my_custom_shortcode' );
if ( ! empty ( $snippet ) ) {
echo 'Found snippet: ' . $snippet ['name' ];
echo 'Code length: ' . strlen ( $snippet ['code' ] ) . ' bytes' ;
}
Example 8: Duplicate a Snippet
<?php
use ADVAN\Entities\Snippet_Entity;
$original_id = 42 ;
$new_id = Snippet_Entity::duplicate ( $original_id );
if ( $new_id ) {
echo 'Created duplicate with ID: ' . $new_id ;
$new_snippet = Snippet_Entity::get_snippet ( $new_id );
echo 'New name: ' . $new_snippet ['name' ];
}
Need User Guide documentation?
See
Snippets Module User Guide for more details about configuration, practical usage and information.