Custom Event Tracking

Available on:
Free
Premium
Marketing Add-on

1. Overview

Custom Events let you capture any interaction—form submissions, feature usage, purchases, etc.—and analyse them beside built‑in WP Statistics metrics. Each event is stored in the wp_statistics_events table and can be triggered from JavaScript (client) or PHP (server).

Important: An event must be registered (UI goal or code filter) before you trigger it; unregistered names are ignored and nothing is written to the database.

2. Registering Custom Events

2.1 Via Marketing Add‑on (UI)

  1. Dashboard → Statistics → Goals → Create Goal
  2. Fill Goal Name (label) and Machine Name (identifier, e.g. gravity_form_submit).
  3. Choose Goal Type: Event, switch Status ON, click Save.

The goal is now registered; proceed to triggering code.

2.2 Programmatically (Core Filter)

No Marketing add‑on required. Hook the wp_statistics_custom_events filter:

/**
 * Register one or more custom events.
 */
function mysite_register_custom_events( $events ) {
    $events[] = [
        'name'         => 'My Custom Event',
        'machine_name' => 'my_custom_event',
        'status'       => true // false disables without removing code
    ];
    return $events;
}
add_filter( 'wp_statistics_custom_events', 'mysite_register_custom_events' );

Add as many array items as you need. Only events with status => true will be stored.

3. Reserved Event Names — Do Not Use

page_view          video_start        custom_event
user_login         session_start      video_progress
analytics          view_search_results user_engagement
video_complete     reserved_event     user_logout
scroll             add_to_cart        tracking_event
form_submit        click              purchase
system_event       file_download      notification_open
error_event

If you need something similar, prefix/suffix it—e.g. shop_purchase_confirmed, cta_click.

4. Reserved Data Keys

KeyAuto‑populated value
visitor_idInternal visitor ID
resource_idPost/Page ID where event fired
user_idLogged‑in WP user ID

How it works
WP Statistics tries to fill these keys automatically whenever it can detect the visitor, page, and user. If you trigger an event in a context where those details are not available—typical with pure PHP or cron jobs—you may include them manually. Only override values that the system could not determine; otherwise leave them out to avoid data drift.

5. Triggering Events

5.1 JavaScript (Client)

// Syntax
wp_statistics_event(eventName, dataObject?);

// Minimal
wp_statistics_event('cta_click');

// With data
wp_statistics_event('cta_click', {
    location: 'hero',
    variant: 'B',
    step: 1
});

5.2 PHP (Server)

// Syntax
wp_statistics_event( $event_name, array $data = [] );

// Example: confirmed order
wp_statistics_event( 'shop_purchase_confirmed', [
    'order_id'    => (int) $order->get_id(),
    'total_cents' => (int) ( $order->get_total() * 100 ),
    'currency'    => $order->get_currency(),
    'user_id'     => (int) $order->get_user_id(),
] );

6. Practical Examples

6.1 Multi‑Step Signup Funnel

function logSignupStep(step, method) {
    wp_statistics_event('signup_step', { step, method });
}

6.2 Feature Adoption Toggle

wp_statistics_event('feature_use', {
    feature: 'dark_mode',
    enabled: true
});

6.3 Gravity Forms Submission

document.addEventListener('gform_confirmation_loaded', e => {
    const formName = e.detail.formTitle || 'unknown_form';
    wp_statistics_event('gravity_form_submit', { form: formName });
});

6.4 Server‑Assured WooCommerce Purchase

add_action( 'woocommerce_order_status_completed', function( $order_id ) {
    $order = wc_get_order( $order_id );
    wp_statistics_event( 'shop_purchase_confirmed', [
        'order_id'    => $order_id,
        'total_cents' => (int) ( $order->get_total() * 100 ),
        'currency'    => $order->get_currency(),
        'user_id'     => $order->get_user_id(),
    ] );
} );

7. Naming & Data Design

ElementRuleExample
Machine Namelowercase, underscores/dashescta_click
Keysshort, predictableplan:"pro", variant:"A"
Valuesstring / int / bool onlystep:2, success:true
No PIIuse IDs; avoid emails, names, raw IPsuser_id:42

8. Reading the Event Report

SectionInsight
Conversion Rate% of sessions producing at least one event run
Event RunsTotal fires; compare periods for growth
Activity TrendDaily line chart—watch for drops after deploys
Pages TablePages generating the event
Dimensions PanelsBrowser, OS, and your custom keys (form, variant, …)
Last ActivitiesReal‑time QA; verify your test events

9. Troubleshooting

SymptomCauseFix
No dataEvent not registered or name mismatchRegister via UI/filter; check spelling
Spike in runsDuplicate listenersDebounce or remove extra handlers
Flat trend after releaseInstrumentation brokenRoll back or patch trigger code

10. Reference Snippets

// Register events via code (optional)
add_filter( 'wp_statistics_custom_events', function ( $events ) {
    $events[] = [ 'name' => 'CTA Click', 'machine_name' => 'cta_click', 'status' => true ];
    $events[] = [ 'name' => 'Signup Step', 'machine_name' => 'signup_step', 'status' => true ];
    return $events;
} );
// Safe wrapper (prevents JS crash if tracking unavailable)
function safeEvent(name, data) {
    try { wp_statistics_event(name, data); } catch(e) {}
}

Happy tracking!

Let’s get started
Take your business to next level

Become part of our growing family of +600,000 users and get the tools you need to make smart choices for your website. Simple, powerful insights are just a click away.