## Tracking Custom Events

Alpha Insights lets you record custom events from the frontend (JavaScript) or the backend (PHP). Custom events appear in your analytics alongside built-in events (page views, add to cart, purchase, etc.) so you can measure conversions, engagement, and business-specific actions.

### Overview

You can track custom events in two ways:

- JavaScript (frontend): Fire events from the browser when the user does something (e.g. click a CTA, play a video, submit a form). Uses the same REST API as the built-in event tracking script.
- PHP (backend): Fire events from server-side code (hooks, shortcodes, templates) when something happens (e.g. form processed, lead captured, custom conversion). Uses a simple wrapper function that fills in session data automatically.

Both methods write to the same events table (`wp_wpd_ai_woocommerce_events`) and respect the same settings (event tracking enabled, user exclusions, rate limiting). For a list of built-in event types, see Event Types Reference.

### Tracking Custom Events from JavaScript (Frontend)

The event tracking script exposes a global function `WpdAiEventTracking()` that sends a single event to the Alpha Insights API. Use it anywhere in your theme or plugin JavaScript after the tracking script has loaded.

#### Basic usage

    WpdAiEventTracking({
        event_type: 'your_custom_event_name',
        event_quantity: 1,           // Optional, default 1
        event_value: 0,              // Optional, default 0
        object_id: 123,              // Optional, default current post ID
        object_type: 'product',      // Optional, default current post type
        product_id: 456,             // Optional, default 0
        variation_id: 789,           // Optional, default 0
        additional_data: {           // Optional, default {}
            custom_field: 'value',
            another_field: 'another_value'
        }
    });

Required: Only `event_type` is required. All other fields are optional and default to the current context (page, post type, etc.) when omitted.

#### Parameter reference (JavaScript)

Parameter | Type | Description
--- | --- | ---
`event_type` | string | Required. Name of the event (e.g. `newsletter_signup`, `video_play`).
`event_quantity` | number | Quantity associated with the event (default: 1).
`event_value` | number | Monetary value if applicable (default: 0).
`object_id` | number | WordPress post/page/object ID (default: current post ID).
`object_type` | string | Post type (e.g. `post`, `page`, `product`).
`product_id` | number | Product ID for product-related events (default: 0).
`variation_id` | number | Variation ID for variable products (default: 0).
`additional_data` | object | Extra key-value data sent as JSON with the event.

#### Example: Track a CTA click

    jQuery('.my-cta-button').on('click', function() {
        WpdAiEventTracking({
            event_type: 'cta_click',
            additional_data: {
                cta_id: jQuery(this).data('cta-id'),
                cta_location: 'hero'
            }
        });
    });

#### Example: Track a form submission (non-cart)

    jQuery('#my-lead-form').on('submit', function() {
        WpdAiEventTracking({
            event_type: 'lead_form_submit',
            object_id: 0,
            object_type: 'form',
            additional_data: {
                form_id: 'my-lead-form',
                form_name: 'Contact'
            }
        });
    });

#### Example: Track a video play

    document.querySelector('#promo-video').addEventListener('play', function() {
        if (typeof WpdAiEventTracking === 'function') {
            WpdAiEventTracking({
                event_type: 'video_play',
                additional_data: {
                    video_id: this.getAttribute('data-video-id'),
                    video_title: 'Product Demo'
                }
            });
        }
    });

#### Notes (JavaScript)

- Events are only sent if event tracking is enabled in Alpha Insights → Settings.
- The tracking script must be loaded on the page (it is enqueued automatically when event tracking is enabled).
- Events are sent asynchronously (sendBeacon or AJAX). There is no need to wait for a response unless you are handling success/error.
- If engaged-session tracking is enabled, the first page view may wait for user interaction; custom events still send immediately when you call `WpdAiEventTracking()`.

### Tracking Custom Events from PHP (Backend)

Use the single function `wpdai_track_custom_event( $event_type, $args )` to record custom events from server-side code (hooks, shortcodes, templates, form handlers). Core params—`session_id`, `ip_address`, `user_id`, and `page_href`—are set automatically from the current session when you don’t pass them. Pass them in `$args` only when you need to override (e.g. server-side or headless context where you have your own session/request context).

#### wpdai_track_custom_event()

    wpdai_track_custom_event( string $event_type, array $args = array() );

Parameters:

- `$event_type` (string, required) — The event type name (e.g. `newsletter_signup`, `download_lead_magnet`, `custom_conversion`).
- `$args` (array, optional) — Event data. Any key you omit is filled from the current session or defaults. Supported keys are listed below.

Returns: An array with `success` (bool), `message` (string), `code` (string), and `rows_inserted` (int). Use this to log or handle failures.

#### $args keys (PHP)

Core params (set automatically from session when not provided; override only if needed):

Key | Type | Description
--- | --- | ---
`session_id` | string | Override session ID. Normally from current Alpha Insights session.
`ip_address` | string | Override IP address. Normally from current request.
`user_id` | int | Override user ID. Normally current logged-in user (or 0).
`page_href` | string | Override page URL. Normally current page (must be same domain for insertion).

Event params:

Key | Type | Description
--- | --- | ---
`event_quantity` | int | Quantity (default: 1).
`event_value` | float | Monetary value (default: 0).
`object_id` | int | WordPress post/page/object ID.
`object_type` | string | Post type (e.g. `post`, `page`, `product`).
`product_id` | int | Product ID for product-related events.
`variation_id` | int | Variation ID for variable products.
`additional_data` | array | Extra key-value data (stored as JSON).

#### Example: Track after form processing (hook)

    add_action( 'my_plugin_lead_submitted', 'wpd_my_track_lead_event', 10, 2 );

    function wpd_my_track_lead_event( $lead_id, $form_data ) {
        wpdai_track_custom_event( 'lead_submitted', array(
            'object_id'       => 0,
            'object_type'     => 'lead_form',
            'additional_data' => array(
                'lead_id'   => $lead_id,
                'form_name' => isset( $form_data['form_name'] ) ? $form_data['form_name'] : '',
            ),
        ) );
    }

#### Example: Track a custom conversion with value

    // After a quote request is saved
    wpdai_track_custom_event( 'quote_request', array(
        'event_value'      => 0,
        'object_id'        => get_the_ID(),
        'object_type'      => get_post_type(),
        'additional_data'  => array(
            'quote_id' => $quote_id,
            'source'   => 'contact_page',
        ),
    ) );

#### Example: Track from a shortcode (e.g. download link page view)

    add_shortcode( 'wpd_track_download', 'wpd_shortcode_track_download' );

    function wpd_shortcode_track_download( $atts ) {
        $atts = shortcode_atts( array(
            'resource_id' => '',
            'label'       => 'Download',
        ), $atts, 'wpd_track_download' );

        $url = get_permalink( $atts['resource_id'] );
        if ( ! $url ) {
            return '';
        }

        // Track that the user saw this download CTA (fires when shortcode is rendered)
        wpdai_track_custom_event( 'resource_download_view', array(
            'object_id'       => (int) $atts['resource_id'],
            'object_type'     => 'resource',
            'additional_data' => array(
                'label' => sanitize_text_field( $atts['label'] ),
            ),
        ) );

        return '<a href="' . esc_url( $url ) . '" class="wpd-download-link">' . esc_html( $atts['label'] ) . '</a>';
    }

To track the actual click or file download, use JavaScript `WpdAiEventTracking()` on the link click, or call `wpdai_track_custom_event()` from a redirect handler that runs when the user hits your download endpoint.

#### Example: Overriding core params (e.g. server-side context)

    // When you have your own session/request context (e.g. webhook or background job)
    wpdai_track_custom_event( 'server_side_conversion', array(
        'session_id'      => $stored_session_id,
        'ip_address'      => $customer_ip,
        'user_id'         => $customer_user_id,
        'page_href'       => home_url( '/thank-you/' ),
        'event_value'     => 99.00,
        'object_id'       => 456,
        'object_type'     => 'product',
        'product_id'      => 456,
        'additional_data' => array( 'campaign' => 'summer_sale' ),
    ) );

If you omit `session_id`, `ip_address`, `user_id`, or `page_href`, they are set automatically from the current Alpha Insights session and request.

#### Notes (PHP)

- Events are not inserted in the admin area, during CRON, or when event tracking is disabled. The same user/role exclusions and rate limits as frontend tracking apply.
- Insertion can fail if there is no valid session/landing page (e.g. server-side-only or headless request). Check the returned `success` and `code` if you need to handle failures.
- Custom event types appear in reports and filters like built-in events; use a consistent naming convention (e.g. snake_case) for easier analysis.

### Viewing Custom Events in Reports

Custom events are stored in the same table as built-in events. In Alpha Insights reports you can:

- Filter or group by `event_type` to see your custom event names.
- Use Website Traffic and event-based metrics to count custom events, events per session, and conversion rates.
- Use `additional_data` in exports or custom queries for deeper segmentation (e.g. by `form_name`, `video_id`).

For a full list of built-in event types and their meanings, see Event Types Reference.