array(
'name' => __('Snippets', 'add-custom-codes'),
'singular_name' => __('Snippet', 'add-custom-codes'),
'add_new' => __('Add New Snippet', 'add-custom-codes'),
'add_new_item' => __('Add New Snippet', 'add-custom-codes'),
'edit_item' => __('Edit Snippet', 'add-custom-codes'),
'new_item' => __('New Snippet', 'add-custom-codes'),
'view_item' => __('View Snippet', 'add-custom-codes'),
'search_items' => __('Search Snippets', 'add-custom-codes'),
'not_found' => __('No snippets found', 'add-custom-codes'),
'not_found_in_trash' => __('No snippets found in trash', 'add-custom-codes'),
'all_items' => __('All Snippets', 'add-custom-codes'),
'menu_name' => __('Add Custom Codes', 'add-custom-codes'),
'name_admin_bar' => __('Snippet', 'add-custom-codes'),
),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
// Restrict management of snippets to administrators (or roles with manage_options)
'capability_type' => 'post',
'capabilities' => array(
'edit_post' => 'manage_options',
'read_post' => 'manage_options',
'delete_post' => 'manage_options',
'edit_posts' => 'manage_options',
'edit_others_posts' => 'manage_options',
'publish_posts' => 'manage_options',
'read_private_posts' => 'manage_options',
'create_posts' => 'manage_options',
'delete_posts' => 'manage_options',
'delete_private_posts' => 'manage_options',
'delete_published_posts' => 'manage_options',
'delete_others_posts' => 'manage_options',
'edit_private_posts' => 'manage_options',
'edit_published_posts' => 'manage_options',
),
'supports' => array('title'),
'menu_icon' => plugins_url('add-custom-codes/assets/images/accodes-menu-icon.svg'),
'menu_position' => 60,
'taxonomies' => array('accodes_tag'),
));
}
add_action('init', 'accodes_register_snippets_cpt');
//register tags
function accodes_register_snippet_tags_taxonomy() {
register_taxonomy('accodes_tag', 'accodes_snippets', array(
'label' => __('Snippet Tags', 'add-custom-codes'),
'labels' => array(
'name' => __('Snippet Tags', 'add-custom-codes'),
'singular_name' => __('Snippet Tag', 'add-custom-codes'),
'search_items' => __('Search Tags', 'add-custom-codes'),
'all_items' => __('All Tags', 'add-custom-codes'),
'edit_item' => __('Edit Tag', 'add-custom-codes'),
'update_item' => __('Update Tag', 'add-custom-codes'),
'add_new_item' => __('Add New Tag', 'add-custom-codes'),
'new_item_name' => __('New Tag Name', 'add-custom-codes'),
'menu_name' => __('Snippet Tags', 'add-custom-codes'),
),
'hierarchical' => false, // set to true if you want category-style nesting
'show_ui' => true,
'show_admin_column' => true,
'show_in_rest' => true,
'rewrite' => array('slug' => 'snippet-tag'),
'show_in_quick_edit' => false,
'meta_box_cb' => false,
));
}
add_action('init', 'accodes_register_snippet_tags_taxonomy');
//remove default tags box on edit screen
add_action('admin_menu', function () {
remove_meta_box('tagsdiv-accodes_tag', 'accodes_snippets', 'side');
});
//add submeanu
add_action('admin_menu', function () {
//global codes page
add_submenu_page(
'edit.php?post_type=accodes_snippets',
'Global Codes',
'Global Codes',
'manage_options',
'accodes-global',
'accodes_global_page_callback'
);
// Import / Export
add_submenu_page(
'edit.php?post_type=accodes_snippets',
'Import / Export Snippets',
'Import / Export',
'manage_options',
'accodes-import-export',
'accodes_import_export_page_callback'
);
//about page
add_submenu_page(
'edit.php?post_type=accodes_snippets',
'About Add Custom Codes',
'About',
'manage_options',
'accodes-about',
'accodes_about_page_callback'
);
});
// Disable block editor and hide content editor
add_filter('use_block_editor_for_post_type', function($use, $type){
return $type === 'accodes_snippets' ? false : $use;
}, 10, 2);
add_action('admin_head', function () {
$screen = get_current_screen();
if ($screen && $screen->post_type === 'accodes_snippets') {
remove_post_type_support('accodes_snippets', 'editor');
}
});
// place Snippet UI right below the title
add_action('edit_form_after_title', function () {
$screen = get_current_screen();
if ($screen->post_type === 'accodes_snippets') {
global $post;
accodes_render_snippet_editor($post);
}
});
// Render snippet UI
function accodes_render_snippet_editor($post) {
$content = get_post_meta($post->ID, '_accodes_code', true);
$language = get_post_meta($post->ID, '_accodes_snippet_language', true) ?: 'php';
$location = get_post_meta($post->ID, '_accodes_snippet_location', true) ?: 'site';
$active = get_post_meta($post->ID, '_accodes_snippet_active', true);
if ($active === '') {
$active = '1'; // default checked for new snippets
}
// If it's a new draft (not published yet), default to active
if ($active === '0' && $post->post_status !== 'publish') {
$active = '1';
}
$notes = get_post_meta($post->ID, '_accodes_snippet_notes', true);
$tags_raw = get_post_meta($post->ID, '_accodes_snippet_tags', true);
$tags_array = $tags_raw ? explode(',', $tags_raw) : [];
$error = get_post_meta($post->ID, '_accodes_snippet_error', true);
if ($error) {
echo '
';
echo esc_html($error);
echo '
';
// Echo JS to uncheck the status toggle
echo "";
}
// Provide safe default templates only when empty
if (trim((string) $content) === '') {
switch ($language) {
case 'javascript':
$content = '/* Add your scripts here. You can remove example code */' . "\n" . 'console.log("code loaded.");' . "\n";
break;
case 'css':
$content = '/* Your CSS here */' . "\n" . '.selector {' . "\n\t\n}" . "\n";
break;
case 'htmlmixed':
$content = '' . "\n" . '' . "\n";
break;
case 'php':
default:
// No explicit PHP open/close tags; runner evaluates raw PHP body.
$content = '// Your PHP here' . "\n";
break;
}
}
?>
How do you want to use the snippet?
post_status === 'publish') ? '' : 'style="display:none;"'; ?>>
Shortcode (Click to copy)
[accodes_snippet id="ID); ?>"]
Shortcode Copied!
post_status === 'publish') ? 'style="display:none;"' : ''; ?>>
Shortcode will be displayed here after you Publish.
Use this field to describe what this snippet does. This won't be shown anywhere publicly.
Classify your snippets using tags. For example, if you are using multiple snippets for Woocommerce, use "Woocommerce" as a tag.
'accodes_snippets',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids', // only IDs to keep the query light
'no_found_rows' => true,
'meta_query' => [
[
'key' => '_accodes_snippet_active',
'value' => '1',
],
[
'key' => '_accodes_snippet_location',
'value' => $location,
],
],
];
$ids = get_posts( $query_args );
if ( ! is_array( $ids ) ) {
$ids = [];
}
// Cache for 5 minutes
set_transient( $cache_key, $ids, 5 * MINUTE_IN_SECONDS );
}
if ( empty( $ids ) ) {
return;
}
// Fetch posts by IDs preserving order
$snippets = get_posts([
'post_type' => 'accodes_snippets',
'post_status' => 'publish',
'posts_per_page' => count( $ids ),
'post__in' => $ids,
'orderby' => 'post__in',
'no_found_rows' => true,
]);
foreach ($snippets as $snippet) {
// Only run snippets created by users with administrative capability
if (!user_can((int) $snippet->post_author, 'manage_options')) {
continue;
}
$language = get_post_meta($snippet->ID, '_accodes_snippet_language', true);
$code = get_post_meta($snippet->ID, '_accodes_code', true);
if (empty($code)) continue;
switch ($language) {
case 'php':
if (!is_admin()) {
$cleaned = preg_replace('/^\s*<\?(php)?/', '', trim($code));
try {
// phpcs:ignore WordPress.Security.EvalDetected -- Intentionally executing admin-authored PHP snippets; access is restricted to administrators (snippet authors must have 'manage_options').
eval( $cleaned );
delete_post_meta( $snippet->ID, '_accodes_snippet_error' ); // clear old errors
} catch ( Throwable $e ) {
// Auto-deactivate the snippet
update_post_meta($snippet->ID, '_accodes_snippet_active', '0');
// Log error
update_post_meta(
$snippet->ID,
'_accodes_snippet_error',
'PHP Error on line ' . $e->getLine() . ': ' . $e->getMessage()
);
}
}
break;
case 'css':
// Intentionally output admin-authored CSS without HTML-encoding so quotes stay intact.
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentionally outputting admin-authored CSS; restricted to manage_options.
echo "\n";
break;
case 'javascript':
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentionally outputting admin-authored JS for a code injection plugin; restricted to manage_options.
echo "\n";
break;
case 'htmlmixed':
default:
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Intentionally outputting admin-authored HTML; restricted to manage_options and sanitized for non-privileged.
echo $code;
break;
}
}
}
// Declare Columns on snippets listing page
function accodes_snippet_columns($columns) {
$columns['accodes_type'] = __('Type', 'add-custom-codes');
$columns['accodes_health'] = __('Snippet Health', 'add-custom-codes');
$columns['accodes_status'] = __('Status', 'add-custom-codes');
return $columns;
}
add_filter('manage_accodes_snippets_posts_columns', 'accodes_snippet_columns');
// Render the columns in snippets listing page
function accodes_snippet_column_content($column, $post_id) {
if ($column === 'accodes_type') {
$lang = get_post_meta($post_id, '_accodes_snippet_language', true);
$badge = '';
switch ($lang) {
case 'php':
$badge = 'PHP';
break;
case 'css':
$badge = 'CSS';
break;
case 'javascript':
$badge = 'JS';
break;
case 'htmlmixed':
default:
$badge = 'HTML';
break;
}
echo wp_kses( $badge, [ 'span' => [ 'class' => [] ] ] );
}
if ($column === 'accodes_health') {
$error = get_post_meta($post_id, '_accodes_snippet_error', true);
if (!empty($error)) {
echo 'i';
} else {
echo '';
}
}
if ($column === 'accodes_status') {
$active = get_post_meta($post_id, '_accodes_snippet_active', true);
$is_checked = ($active === '1');
echo '
';
}
}
add_action('manage_accodes_snippets_posts_custom_column', 'accodes_snippet_column_content', 10, 2);
//change Snippet status on Status toggle click (List snippets page)
add_action('wp_ajax_accodes_toggle_snippet_status', function () {
check_ajax_referer('accodes_toggle_snippet');
$post_id = isset($_POST['post_id']) ? intval( wp_unslash($_POST['post_id']) ) : 0;
$active_raw = isset($_POST['active']) ? sanitize_text_field( wp_unslash($_POST['active']) ) : null;
$active = ($active_raw === '1') ? '1' : '0';
if ($post_id && get_post_type($post_id) === 'accodes_snippets') {
if (!current_user_can('edit_post', $post_id)) {
wp_send_json_error(['message' => 'Permission denied'], 403);
}
update_post_meta($post_id, '_accodes_snippet_active', $active);
wp_send_json_success(['status' => $active]);
}
wp_send_json_error(['message' => 'Invalid post ID or type']);
});
//create shortcode option for html
add_action('init', function () {
add_shortcode('accodes_snippet', function ($atts) {
$atts = shortcode_atts(['id' => 0], $atts);
$post_id = intval($atts['id']);
if (!$post_id || get_post_type($post_id) !== 'accodes_snippets') return '';
$snippet = get_post($post_id);
if (!$snippet || !user_can((int) $snippet->post_author, 'manage_options')) return '';
$location = get_post_meta($post_id, '_accodes_snippet_location', true);
$active = get_post_meta($post_id, '_accodes_snippet_active', true);
$content = get_post_meta($post_id, '_accodes_code', true);
$language = get_post_meta($post_id, '_accodes_snippet_language', true);
if ($location === 'shortcode' && $active === '1' && $language === 'htmlmixed') {
return $content;
}
return ''; // fallback: do nothing
});
});
//put snippets on site
add_action('admin_footer', function () {
if (is_admin()) accodes_inject_snippets('admin');
});
add_action('wp_body_open', function () {
if (!is_admin()) accodes_inject_snippets('site');
});
add_action('wp_footer', function () {
if (!is_admin()) accodes_inject_snippets('footer');
});
add_action('wp_head', function () {
accodes_inject_snippets('head');
});