Developer documentation

OCodeInsert v1.1.0

Insert custom HTML, JavaScript, and CSS into any page without touching theme files. Snippets survive theme updates, target by page type, URL, and user — with safe mode to prevent site breakage.

WordPress plugin No database tables Free + Pro v1.1.0 · 2025-04-24
01 · Overview

What OCodeInsert does

A lightweight alternative to editing functions.php or installing bloated tools like WPCode — built for inserting snippets that survive theme updates and stay organised.

🏷️
Three snippet types
HTML (raw), JavaScript (auto-wrapped in <script>), CSS (auto-wrapped in <style>)
📍
4 injection locations
Site head, before content, after content, footer
🎯
Full targeting
Page type, URL pattern, user condition (all / logged-in / logged-out)
🛡️
Safe mode
Global toggle + per-request ?oci_safe=1 URL bypass
✏️
CodeMirror editor
Syntax highlighting for HTML, JS, CSS via wp-codemirror
🗄️
No custom tables
Stored in wp_options — lightweight, portable, easy to back up
OCodeInsert replaces the need for editing functions.php, header.php, bloated alternatives like WPCode / Insert Headers and Footers, or relying on theme option panels for script injection.
02 · Installation

Getting installed

From WordPress admin

1
Go to Plugins → Add New → Upload Plugin.
2
Upload ocodeinsert.zip and click Install Now, then Activate.

Manual (FTP / SFTP)

1
Extract ocodeinsert.zip.
2
Upload the ocodeinsert/ folder to /wp-content/plugins/.
3
Activate via Plugins → Installed Plugins.
💡On activation, OCodeInsert writes default settings to wp_options. No database tables are created. The plugin is immediately ready to use.
03 · Quick Start

Up and running in minutes

Adding your first snippet — a Google Analytics 4 script injected into every page's <head>.

1
Click OCodeInsert in the WordPress sidebar.
2
Click + New Snippet.
3
Enter a title — e.g. Google Analytics.
4
Select Type → JavaScript and Location → Site Head.
5
Paste your GA4 script into the code editor. Leave Page Types as All Pages.
6
Toggle Activate this snippet on and click Save Snippet.

The script now appears inside <head> on every page, automatically wrapped in <script> tags.

04 · Types, Locations & Targeting

Types, locations & targeting

Snippet types

TypeBadgeAuto-wrap behaviour
htmlHTMLRaw output — no wrapping applied
jsJavaScriptWraps bare JS in <script>…</script>. If code already starts with <script, skipped.
cssCSSWraps bare CSS in <style>…</style>. If code already starts with <style, skipped.

The Type field drives syntax highlighting, auto-wrap logic, and the visual badge in the list. It does not control where the snippet runs — that is Location.

Injection locations

wp_head · priority 1
Site Head
Analytics, tracking pixels, preconnect hints — inside <head>
the_content filter
Before Content
Only fires on singular templates. JS fallback via wp_footer for page builders.
the_content filter
After Content
Only fires on singular templates. JS fallback finds last <p> in article body.
wp_footer · priority 1
Footer
Before </body>. Chat widgets, deferred scripts.
ℹ️Before/After Content fallback: If a theme or page builder bypasses the_content filter, OCodeInsert fires a JS fallback via wp_footer that finds the first and last <p> in the article body.

Page type targeting

ValueMatches
allEvery page (default) — overrides all others when selected
frontFront page — is_front_page()
singleSingle posts, pages, CPTs — is_singular()
archiveCategory, tag, date archives + blog index
searchSearch results — is_search()
404404 error page — is_404()

URL pattern targeting

Comma-separated URL paths relative to the domain root. Matched against $_SERVER['REQUEST_URI']. Case-insensitive, trailing slashes ignored. Applied in addition to Page Type — both must pass.

/about, /blog/*, /shop/product-category/*
PatternMatches
/about/about and /about/ only
/blog/*/blog/, /blog/my-post, /blog/2024/01/post
/shop/*, /cartAny URL under /shop/ plus exactly /cart

User condition & priority

SettingValueBehaviour
User conditionallAll visitors (default)
logged_inLogged-in users only
logged_outLogged-out visitors only
Priority1–99Controls injection order within the same location. Lower = earlier. Default: 10.
05 · Admin Interface

Admin interface

Navigate to OCodeInsert in the WordPress sidebar. Single menu entry — no submenu interference.

Snippets list columns

ColumnDescription
StatusToggle Active (green) / Paused (grey) without reloading the page
TitleSnippet name
TypeHTML JavaScript CSS badge
LocationInjection point
TargetingPage type + user condition summary
PriorityNumeric priority within the location
ActionsEdit · Duplicate · Export JSON · Delete

The filter toolbar supports live search by title (client-side) and filtering by Type, Status, and Location.

Snippet editor

Click + New Snippet or the edit icon on any row. The modal contains: Basic Info (title, type, location, priority), CodeMirror code editor (mode switches on type change), Targeting (page types, URL patterns, user condition), and an Active checkbox to save as draft.

Duplicate & export

Duplicate: Click the copy icon in Actions. The copy gets a new ID, (Copy) appended to the title, and is saved as inactive by default.

Export single snippet Free: Click the download icon to export a snippet as .json, generated client-side.

JSON{
  "id":             "...",
  "title":          "My Snippet",
  "type":           "js",
  "code":           "console.log('hello');",
  "location":       "head",
  "active":         true,
  "priority":       10,
  "pages":          "",
  "page_types":     ["all"],
  "user_condition": "all",
  "created":        "2025-01-01 12:00:00"
}
06 · Settings Page

Settings page

Navigate to OCodeInsert → Settings via the top navigation tabs.

Global enable / disable

Master switch for the entire plugin. When disabled: no snippets are injected anywhere, the admin interface remains accessible, and all snippet data is preserved. Useful for temporary maintenance or debugging without deactivating the plugin.

Role permissions

Choose which WordPress roles can access the OCodeInsert admin panel. Administrators always have access. Default: Administrators only. Adding Editor lets editors manage snippets without full admin access.

Error log

Maintains an internal log of issues during snippet processing (max 50 entries). Columns: Time, Snippet ID, Message. Click Clear Log to delete all entries.

07 · Safe Mode

Safe mode

Safe mode suspends all snippet output globally to protect your site when a snippet causes unexpected issues.

Activating safe mode

MethodEffect
Admin toggleOCodeInsert → Settings → enable Safe Mode → Save. Affects all visitors. An amber notice bar appears in the snippets admin.
URL parameterAppend ?oci_safe=1 to any frontend URL. Disables snippets for that request only — no other visitors are affected.
https://example.com/my-page/?oci_safe=1

Diagnosing issues

1
Use ?oci_safe=1 to confirm the issue is snippet-related.
2
Go to the Snippets list and pause snippets one by one to isolate the problem.
3
Edit the faulty snippet and correct the code.
4
Re-activate the snippet.

Evaluation order

All conditions must pass for a snippet to be injected:

  • 1Is the plugin globally enabled?
  • 2Is Safe Mode active?
  • 3Is ?oci_safe=1 in the current URL?
  • 4Does the snippet pass page type targeting?
  • 5Does the snippet pass user condition?
  • 6Does the snippet pass URL pattern matching?
  • 7Is the snippet set to active?
08 · CodeMirror Editor

CodeMirror editor

OCodeInsert uses WordPress's built-in CodeMirror editor (wp-codemirror) — no external CDN or library dependencies. Loaded only on the Snippets page, not the Settings page.

  • Syntax highlighting for HTML, JavaScript, and CSS
  • Line numbers
  • Bracket and tag matching
  • Auto-indent
  • Mode switches automatically when you change the Type dropdown
TypeCodeMirror mode
HTMLtext/html — HTML mixed mode, supports embedded JS and CSS
JavaScripttext/javascript
CSStext/css
09 · Data Storage & Uninstall

Data storage & uninstall

OCodeInsert uses WordPress wp_options exclusively — no custom database tables. All snippets load from a single get_option() call per page load.

Options stored

Option keyContents
oci_code_snippetsJSON-encoded array of all snippets
oci_settingsPlugin settings: enabled, safe_mode, allowed_roles
oci_error_logArray of error log entries (max 50)

Snippet schema

JSON{
  "id":             "uuid-v4",
  "title":          "string",
  "type":           "html | js | css",
  "code":           "string (raw code)",
  "location":       "head | before_content | after_content | footer",
  "active":         true,
  "priority":       10,
  "pages":          "comma-separated URL patterns or empty string",
  "page_types":     ["all"],
  "user_condition": "all | logged_in | logged_out",
  "created":        "Y-m-d H:i:s"
}
ℹ️Optimal for up to ~50 snippets. OCodeInsert Pro automatically migrates to a dedicated database table when the count exceeds 50.

Uninstall

Deleting via Plugins → Delete (not just deactivating) runs uninstall.php and removes oci_code_snippets, oci_settings, and oci_error_log.

⚠️Deactivating does NOT delete any data. Only deleting the plugin triggers cleanup.
10 · Pro Features

OCodeInsert Pro

Pro features are visible in the free UI with a PRO badge but non-functional until upgraded.

PROExport All / Import
Export all snippets as a single .json bundle. Import single snippets or bundles — imported with new UUIDs, saved inactive by default.
PRODevice Conditions
Target by device type via HTTP_USER_AGENT: all, mobile + tablet, or desktop browsers.
PROUser Role Targeting
Target snippets to specific WordPress roles — more granular than the basic logged-in/out condition.
PRODate Scheduling
Start and/or end date per snippet. Useful for campaign pixels, promotional banners, and time-limited widgets.
PRORevision History
Last 5 saved versions of each snippet's code. View diffs and restore any previous version with one click.
PROSnippet Library
Pre-configured snippets ready to import: GA4, GTM, Meta Pixel, Hotjar, Intercom, Crisp, Cloudflare Analytics, CSS Reset.
PROFolder Organization
Group snippets into named folders (e.g. Analytics, Chat Widgets). Filterable in the list — ideal for 20+ snippets.
PROWP-CLI
wp oci list, toggle, disable-all, safe-mode, export, import commands.

WP-CLI commands (Pro)

BASHwp oci list                          # List all snippets
wp oci list --status=active          # Active snippets only
wp oci toggle <snippet-id>          # Toggle on/off by ID
wp oci disable-all                   # Disable all snippets
wp oci safe-mode on                  # Enable safe mode
wp oci export --file=snippets.json   # Export all snippets
wp oci import --file=snippets.json   # Import snippets
11 · Developer Reference

Developer reference

All PHP methods are static and available after init.

PHP API — OCI_Snippets

PHP// Get all snippets
$snippets = OCI_Snippets::get_all();

// Get a single snippet by UUID
$snippet = OCI_Snippets::get_by_id( 'uuid' );

// Save (create or update)
$id = OCI_Snippets::save_snippet([
    'id'             => '',        // empty = create new
    'title'          => 'My Script',
    'type'           => 'js',      // html | js | css
    'code'           => 'alert(1);',
    'location'       => 'footer',  // head | before_content | after_content | footer
    'active'         => true,
    'priority'       => 10,
    'pages'          => '',        // comma-separated URL patterns
    'page_types'     => ['all'],
    'user_condition' => 'all',     // all | logged_in | logged_out
]);

// Delete
OCI_Snippets::delete_snippet( 'uuid' );

// Toggle active state — returns new state (bool)
$is_active = OCI_Snippets::toggle_snippet( 'uuid' );

// Force-disable (always sets active=false)
OCI_Snippets::disable_snippet( 'uuid' );

// Duplicate — returns new ID
$new_id = OCI_Snippets::duplicate_snippet( 'uuid' );

PHP API — OCI_Settings

PHP$settings   = OCI_Settings::get_all();
$enabled    = OCI_Settings::is_enabled();
$safe_mode  = OCI_Settings::is_safe_mode();
$can_access = OCI_Settings::can_access();

// Error log
OCI_Settings::log_error( 'uuid', 'Error message' );
$log = OCI_Settings::get_error_log();
OCI_Settings::clear_error_log();

AJAX endpoints

All endpoints require nonce (from ociAdmin.nonce) and manage_options capability. Return wp_send_json_success() or wp_send_json_error().

ActionParametersResponse
oci_save_snippetsnippet_id, title, type, code, location, active, priority, pages, page_types[], user_condition{id, snippet}
oci_delete_snippetsnippet_id{}
oci_toggle_snippetsnippet_id{active: bool}
oci_duplicate_snippetsnippet_id{id, snippet}
oci_import_snippetsjson (string){imported: int}
oci_save_settingsenabled, safe_mode, allowed_roles[]{}
oci_clear_error_log{}

Constants

ConstantDefaultPurpose
OCI_VERSION'1.1.0'Plugin version string
OCI_DIRplugin_dir_path(__FILE__)Absolute path to plugin directory
OCI_URLplugin_dir_url(__FILE__)URL to plugin directory
OCI_PROfalseSet to true when a Pro license is active
PHP// Enable Pro features in a custom build (wp-config.php or must-use plugin)
define( 'OCI_PRO', true );

Hooks (Pro)

PHP// Action: fires before a snippet is injected
add_action( 'oci_before_inject', function( array $snippet, string $location ) {
    // $location = 'head' | 'before_content' | 'after_content' | 'footer'
}, 10, 2 );

// Filter: decide whether a snippet should be injected
add_filter( 'oci_should_inject', function( bool $should, array $snippet ): bool {
    if ( $snippet['title'] === 'My Script' ) return false;
    return $should;
}, 10, 2 );

// Helper: get all active snippets for a location
$snippets = oci_get_snippets( 'head' );
12 · Changelog

What's changed

v1.1.0 2025-04-24
  • NewSnippet type field — HTML / JavaScript / CSS
  • NewAuto-wrap JavaScript in <script> tags
  • NewAuto-wrap CSS in <style> tags
  • NewPage type targeting (front, single, archive, search, 404)
  • NewUser condition targeting (all / logged-in / logged-out)
  • NewFourth injection location: Footer (wp_footer)
  • NewDuplicate snippet button
  • NewExport single snippet as JSON (free)
  • NewImport snippets from JSON (Pro)
  • NewExport all snippets as JSON bundle (Pro)
  • NewSafe mode — global toggle and ?oci_safe=1 URL bypass
  • NewSettings page — global enable/disable, safe mode, role permissions
  • NewError log in settings (max 50 entries)
  • NewCodeMirror syntax highlighting editor via wp-codemirror
  • NewLive search and filter toolbar in snippets list
  • NewLight/dark mode toggle with localStorage persistence
  • NewFull admin redesign — brand bar, top nav tabs, v2 design system
  • NewClean uninstall.php — removes all options on plugin deletion
  • NewPro feature stubs with upsell UI and Snippet Library card
  • FixNavigation now uses tab-based routing — single WP sidebar entry, no submenu interference
v1.0.0 Initial release
  • NewSnippet storage in WP options
  • New3 injection locations (head, before content, after content)
  • NewPriority system
  • NewURL pattern targeting
  • NewActive/inactive toggle
  • NewAJAX admin (save, delete, toggle)
13 · FAQ

Frequently asked questions

Will my snippets survive a plugin update?
Yes. Snippets are stored in wp_options, not plugin files. Updating or reinstalling the plugin does not delete snippet data.
Will deactivating the plugin remove my snippets?
No. Deactivating only stops injection. Data is preserved. Only deleting the plugin triggers cleanup.
Why is my snippet not showing on the page?
Check in this order: (1) Is the plugin globally enabled? (2) Is Safe Mode active? (3) Is the snippet toggled Active? (4) Does the page match the Page Type setting? (5) Does the URL match the URL Pattern (if set)? (6) Does the user match the User Condition? (7) If using before_content or after_content, does the theme use the_content filter?
Can I use PHP in snippets?
No. OCodeInsert outputs raw HTML, JavaScript, and CSS only. Use the Code Snippets plugin or functions.php for PHP.
Does OCodeInsert work with page builders (Elementor, Divi, Beaver Builder)?
head and footer locations always work. For before_content / after_content, if the page builder bypasses the_content filter, OCodeInsert's JS fallback handles injection. For most page builders, use head or footer for maximum reliability.
How many snippets can I have?
No hard limit. Storing up to ~50 snippets in wp_options is optimal. OCodeInsert Pro automatically migrates to a dedicated database table when the count exceeds 50.
What happens if I paste JavaScript without <script> tags?
OCodeInsert auto-wraps it. Set Type to JavaScript and paste raw JS — the plugin adds the tags automatically.
How do I temporarily disable all snippets for debugging?
Two options: (1) Go to Settings, enable Safe Mode, save — affects all visitors. (2) Add ?oci_safe=1 to any URL to disable snippets for just that page load without affecting other visitors.
Where is snippet data stored?
In wp_options under oci_code_snippets as a JSON-encoded array. Do not edit it directly.
Can I import snippets from WPCode?
Not directly — WPCode uses a different format. Copy snippet code from WPCode and create new snippets in OCodeInsert manually.
✦ Need help?

Got a question about OCodeInsert?

Reach out directly — Kenneth replies within 24 hours.