Active Analytics Documentation – Events

General Settings Event Settings

Overview

Active Analytics Events allows you to track custom user interactions and behaviors beyond simple pageviews. This powerful feature helps you understand how users interact with your website, from button clicks to form submissions, video plays, and e-commerce transactions.

Table of Contents

Getting Started

Prerequisites

  • Active Analytics plugin installed and activated
  • Events feature enabled in plugin settings
  • Basic knowledge of JavaScript

Enabling Events

  1. Go to Active Analytics > Settings
  2. Navigate to the Events tab
  3. Enable event tracking
  4. Save your settings

Basic Usage

The wpaa() Function

The core of event tracking is the wpaa() JavaScript function:

wpaa('send', 'event', {
    eventCategory: 'Button',
    eventAction: 'Click',
    eventLabel: 'Sign Up Button',
    eventValue: 1
});

Simple Preset Events

For common actions, you can use preset events:

// User registration
wpaa('send', 'register');

// User login
wpaa('send', 'login');

// File download
wpaa('send', 'download');

// Newsletter signup
wpaa('send', 'newsletter');

Event Structure

Required Parameters

  • eventCategory: The category of the event (e.g., ‘Button’, ‘Form’, ‘Video’)
  • eventAction: The action performed (e.g., ‘Click’, ‘Submit’, ‘Play’)
  • eventLabel: Optional descriptive label
  • eventValue: Optional numeric value

Event Data Storage

Events are stored in the wp_wpaa_events table with the following structure:

FieldTypeDescription
idINTAuto-increment primary key
timestampINTUnix timestamp
event_typeVARCHARType of event (usually ‘event’)
event_categoryVARCHAREvent category
event_actionVARCHAREvent action
event_labelVARCHAREvent label
event_valueINTEvent value
urlVARCHARPage URL where event occurred

Implementation Examples

1. JavaScript File Implementation

Create a custom JavaScript file and enqueue it in your theme:

File: /assets/js/analytics-events.js

// Button click tracking
document.addEventListener('DOMContentLoaded', function() {
    // Track CTA button clicks
    const ctaButtons = document.querySelectorAll('.cta-button');
    ctaButtons.forEach(button => {
        button.addEventListener('click', function() {
            wpaa('send', 'event', {
                eventCategory: 'Button',
                eventAction: 'Click',
                eventLabel: this.textContent.trim(),
                eventValue: 1
            });
        });
    });

    // Track navigation menu clicks
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            wpaa('send', 'event', {
                eventCategory: 'Navigation',
                eventAction: 'Click',
                eventLabel: this.textContent.trim()
            });
        });
    });

    // Track external link clicks
    const externalLinks = document.querySelectorAll('a[href^="http"]:not([href*="' + window.location.hostname + '"])');
    externalLinks.forEach(link => {
        link.addEventListener('click', function() {
            wpaa('send', 'event', {
                eventCategory: 'External Link',
                eventAction: 'Click',
                eventLabel: this.href
            });
        });
    });
});

Enqueue in functions.php:

function enqueue_analytics_events() {
    wp_enqueue_script(
        'analytics-events',
        get_template_directory_uri() . '/assets/js/analytics-events.js',
        array(),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_analytics_events');

2. Custom Plugin Implementation

File: /wp-content/plugins/my-analytics-events/my-analytics-events.php

<?php
/**
 * Plugin Name: My Analytics Events
 * Description: Custom event tracking for Active Analytics
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

class MyAnalyticsEvents {

    public function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('wp_footer', array($this, 'add_tracking_code'));
    }

    public function enqueue_scripts() {
        wp_enqueue_script(
            'my-analytics-events',
            plugin_dir_url(__FILE__) . 'assets/analytics-events.js',
            array(),
            '1.0.0',
            true
        );
    }

    public function add_tracking_code() {
        ?>
        <script>
        // Track scroll depth
        let scrollDepth = 0;
        window.addEventListener('scroll', function() {
            const currentDepth = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);
            if (currentDepth > scrollDepth && currentDepth % 25 === 0) {
                wpaa('send', 'event', {
                    eventCategory: 'Engagement',
                    eventAction: 'Scroll',
                    eventLabel: currentDepth + '%'
                });
                scrollDepth = currentDepth;
            }
        });

        // Track time on page
        let startTime = Date.now();
        window.addEventListener('beforeunload', function() {
            const timeOnPage = Math.round((Date.now() - startTime) / 1000);
            wpaa('send', 'event', {
                eventCategory: 'Engagement',
                eventAction: 'Time on Page',
                eventLabel: timeOnPage + ' seconds'
            });
        });
        </script>
        <?php
    }
}

new MyAnalyticsEvents();

3. Functions.php Implementation

Add to your theme’s functions.php:

// Track WooCommerce product views
add_action('woocommerce_single_product_summary', 'track_product_view', 5);
function track_product_view() {
    global $product;
    if ($product) {
        ?>
        <script>
        wpaa('send', 'event', {
            eventCategory: 'E-commerce',
            eventAction: 'Product View',
            eventLabel: '<?php echo esc_js($product->get_name()); ?>',
            eventValue: <?php echo $product->get_price(); ?>
        });
        </script>
        <?php
    }
}

// Track form submissions
add_action('wp_footer', 'track_form_submissions');
function track_form_submissions() {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const forms = document.querySelectorAll('form');
        forms.forEach(form => {
            form.addEventListener('submit', function() {
                wpaa('send', 'event', {
                    eventCategory: 'Form',
                    eventAction: 'Submit',
                    eventLabel: this.id || 'Unnamed Form'
                });
            });
        });
    });
    </script>
    <?php
}

4. Google Tag Manager Implementation

GTM Custom HTML Tag:

<script>
// Track button clicks
document.addEventListener('click', function(e) {
    if (e.target.matches('.track-button')) {
        wpaa('send', 'event', {
            eventCategory: 'Button',
            eventAction: 'Click',
            eventLabel: e.target.textContent.trim()
        });
    }
});

// Track video interactions
document.addEventListener('play', function(e) {
    if (e.target.tagName === 'VIDEO') {
        wpaa('send', 'event', {
            eventCategory: 'Video',
            eventAction: 'Play',
            eventLabel: e.target.src
        });
    }
}, true);
</script>

E-commerce Integration

WooCommerce Events

File: /wp-content/plugins/woo-analytics-events/woo-analytics-events.php

<?php
/**
 * WooCommerce Analytics Events
 */

class WooAnalyticsEvents {

    public function __construct() {
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
        add_action('woocommerce_add_to_cart', array($this, 'track_add_to_cart'), 10, 6);
        add_action('woocommerce_thankyou', array($this, 'track_purchase'));
    }

    public function enqueue_scripts() {
        if (is_woocommerce()) {
            wp_enqueue_script('woo-analytics-events', plugin_dir_url(__FILE__) . 'assets/woo-events.js', array(), '1.0.0', true);
        }
    }

    public function track_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
        $product = wc_get_product($product_id);
        ?>
        <script>
        wpaa('send', 'event', {
            eventCategory: 'E-commerce',
            eventAction: 'Add to Cart',
            eventLabel: '<?php echo esc_js($product->get_name()); ?>',
            eventValue: <?php echo $product->get_price() * $quantity; ?>
        });
        </script>
        <?php
    }

    public function track_purchase($order_id) {
        $order = wc_get_order($order_id);
        $total = $order->get_total();
        ?>
        <script>
        wpaa('send', 'event', {
            eventCategory: 'E-commerce',
            eventAction: 'Purchase',
            eventLabel: 'Order #<?php echo $order_id; ?>',
            eventValue: <?php echo $total; ?>
        });
        </script>
        <?php
    }
}

new WooAnalyticsEvents();

WooCommerce JavaScript Events:

// Track cart interactions
document.addEventListener('DOMContentLoaded', function() {
    // Add to cart button clicks
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('add_to_cart_button')) {
            const productName = e.target.closest('.product').querySelector('.woocommerce-loop-product__title').textContent;
            wpaa('send', 'event', {
                eventCategory: 'E-commerce',
                eventAction: 'Add to Cart Click',
                eventLabel: productName
            });
        }
    });

    // Cart page events
    if (document.body.classList.contains('woocommerce-cart')) {
        // Track cart updates
        const updateCartBtn = document.querySelector('.update-cart');
        if (updateCartBtn) {
            updateCartBtn.addEventListener('click', function() {
                wpaa('send', 'event', {
                    eventCategory: 'E-commerce',
                    eventAction: 'Update Cart',
                    eventLabel: 'Cart Updated'
                });
            });
        }

        // Track proceed to checkout
        const checkoutBtn = document.querySelector('.checkout-button');
        if (checkoutBtn) {
            checkoutBtn.addEventListener('click', function() {
                wpaa('send', 'event', {
                    eventCategory: 'E-commerce',
                    eventAction: 'Begin Checkout',
                    eventLabel: 'Proceed to Checkout'
                });
            });
        }
    }
});

Easy Digital Downloads (EDD) Events

// Track EDD downloads
add_action('edd_complete_download_purchase', 'track_edd_purchase', 10, 3);
function track_edd_purchase($payment_id, $payment_type, $meta) {
    $download_id = $meta['downloads'][0]['id'];
    $download = new EDD_Download($download_id);
    ?>
    <script>
    wpaa('send', 'event', {
        eventCategory: 'E-commerce',
        eventAction: 'Purchase',
        eventLabel: '<?php echo esc_js($download->get_name()); ?>',
        eventValue: <?php echo edd_get_payment_amount($payment_id); ?>
    });
    </script>
    <?php
}

// Track EDD cart events
add_action('wp_footer', 'track_edd_cart_events');
function track_edd_cart_events() {
    if (edd_is_checkout()) {
        ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Track checkout page view
            wpaa('send', 'event', {
                eventCategory: 'E-commerce',
                eventAction: 'Checkout View',
                eventLabel: 'EDD Checkout'
            });

            // Track purchase button click
            const purchaseBtn = document.querySelector('#edd-purchase-button');
            if (purchaseBtn) {
                purchaseBtn.addEventListener('click', function() {
                    wpaa('send', 'event', {
                        eventCategory: 'E-commerce',
                        eventAction: 'Purchase Click',
                        eventLabel: 'EDD Purchase'
                    });
                });
            }
        });
        </script>
        <?php
    }
}

FluentCart Events

Note: FluentCart is a newer WordPress e-commerce plugin with over 315 actions and filters available, but their developer documentation is still under development. Here are the available integration methods:

Available Integration Options:

  1. REST API Integration: FluentCart provides a REST API for programmatic access to orders, products, and customers
  2. Webhooks: Support for triggering external actions based on FluentCart events
  3. Custom Hooks: Over 315 actions and filters available for custom development

Implementation Approaches:

Method 1: Using FluentCart’s REST API

// Track order completion via REST API
fetch('/wp-json/fluentcart/v1/orders/' + orderId)
    .then(response => response.json())
    .then(order => {
        wpaa('send', 'event', {
            eventCategory: 'E-commerce',
            eventAction: 'Purchase',
            eventLabel: 'FluentCart Order #' + order.id,
            eventValue: order.total
        });
    });

Method 2: Using Webhooks

// Set up webhook endpoint to receive FluentCart events
add_action('rest_api_init', 'register_fluentcart_webhook');
function register_fluentcart_webhook() {
    register_rest_route('fluentcart/v1', '/webhook', array(
        'methods' => 'POST',
        'callback' => 'handle_fluentcart_webhook'
    ));
}

function handle_fluentcart_webhook($request) {
    $data = $request->get_json_params();

    if ($data['event'] === 'order.completed') {
        ?>
        <script>
        wpaa('send', 'event', {
            eventCategory: 'E-commerce',
            eventAction: 'Purchase',
            eventLabel: 'FluentCart Order #<?php echo $data['order_id']; ?>',
            eventValue: <?php echo $data['total']; ?>
        });
        </script>
        <?php
    }
}

Method 3: Custom Hook Implementation

// Example - verify actual hook names with FluentCart support
add_action('fluentcart_order_completed', 'track_fluentcart_purchase', 10, 1);
function track_fluentcart_purchase($order) {
    ?>
    <script>
    wpaa('send', 'event', {
        eventCategory: 'E-commerce',
        eventAction: 'Purchase',
        eventLabel: 'FluentCart Order #<?php echo $order->id; ?>',
        eventValue: <?php echo $order->total; ?>
    });
    </script>
    <?php
}

Resources for FluentCart Integration:

Recommendation: Contact FluentCart support directly for the most current hook names and implementation examples, as their documentation is actively being developed.

Form Integration

Gravity Forms Events

// Track Gravity Forms submissions
add_action('gform_after_submission', 'track_gravity_form_submission', 10, 2);
function track_gravity_form_submission($entry, $form) {
    ?>
    <script>
    wpaa('send', 'event', {
        eventCategory: 'Form',
        eventAction: 'Submit',
        eventLabel: '<?php echo esc_js($form['title']); ?>',
        eventValue: <?php echo $entry['id']; ?>
    });
    </script>
    <?php
}

// Track Gravity Forms page views
add_action('wp_footer', 'track_gravity_forms_views');
function track_gravity_forms_views() {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const gravityForms = document.querySelectorAll('.gform_wrapper');
        gravityForms.forEach(form => {
            const formTitle = form.querySelector('.gform_title');
            if (formTitle) {
                wpaa('send', 'event', {
                    eventCategory: 'Form',
                    eventAction: 'View',
                    eventLabel: formTitle.textContent.trim()
                });
            }
        });
    });
    </script>
    <?php
}

Contact Form 7 Events

// Track Contact Form 7 submissions
document.addEventListener('wpcf7mailsent', function(event) {
    const form = event.target;
    const formTitle = form.querySelector('input[name="_wpcf7"]').value;

    wpaa('send', 'event', {
        eventCategory: 'Form',
        eventAction: 'Submit',
        eventLabel: 'Contact Form 7 - ' + formTitle
    });
});

// Track form validation errors
document.addEventListener('wpcf7invalid', function(event) {
    wpaa('send', 'event', {
        eventCategory: 'Form',
        eventAction: 'Validation Error',
        eventLabel: 'Contact Form 7'
    });
});

Event Categories Reference

Standard Categories

CategoryDescriptionCommon Actions
ButtonButton clicks and interactionsClick, Hover, Focus
FormForm interactionsSubmit, Reset, Validation Error
NavigationMenu and link clicksClick, Hover
VideoVideo player interactionsPlay, Pause, Complete, Seek
DownloadFile downloadsDownload, View
E-commerceShopping and purchase eventsAdd to Cart, Purchase, Remove from Cart
EngagementUser engagement metricsScroll, Time on Page, Exit Intent
SocialSocial media interactionsShare, Like, Follow
SearchSearch functionalitySearch, Filter, Sort
ContentContent interactionsView, Read, Share

E-commerce Specific Categories

CategoryDescriptionActions
ProductProduct-related eventsView, Add to Cart, Remove from Cart, Wishlist
CartShopping cart eventsAdd, Remove, Update, Clear
CheckoutCheckout process eventsBegin, Step Complete, Abandon
PurchasePurchase completionComplete, Refund, Cancel
PromotionPromotional eventsView, Click, Apply

Website-Specific Categories

CategoryDescriptionActions
BlogBlog content eventsView Post, Comment, Share
NewsletterNewsletter eventsSubscribe, Unsubscribe, Open
ContactContact form eventsSubmit, View, Error
SupportSupport and help eventsView FAQ, Submit Ticket, Rate
AccountUser account eventsRegister, Login, Logout, Profile Update

Best Practices

1. Consistent Naming

Use consistent, descriptive names for categories and actions:

// Good
wpaa('send', 'event', {
    eventCategory: 'Button',
    eventAction: 'Click',
    eventLabel: 'Header CTA Button'
});

// Avoid
wpaa('send', 'event', {
    eventCategory: 'btn',
    eventAction: 'clk',
    eventLabel: 'cta1'
});

2. Meaningful Labels

Use descriptive labels that provide context:

// Good
eventLabel: 'Product Page - Add to Cart Button'

// Avoid
eventLabel: 'Button'

3. Appropriate Values

Use numeric values for quantifiable events:

// Good - for purchase events
eventValue: 29.99

// Good - for engagement events
eventValue: 1

// Avoid - for non-quantifiable events
eventValue: 'high'

4. Event Timing

Track events at the right moment:

// Track after successful action
document.getElementById('newsletter-form').addEventListener('submit', function(e) {
    // Wait for form submission to complete
    setTimeout(() => {
        wpaa('send', 'event', {
            eventCategory: 'Form',
            eventAction: 'Submit',
            eventLabel: 'Newsletter Signup'
        });
    }, 100);
});

5. Error Handling

Always include error handling:

function trackEvent(category, action, label, value) {
    try {
        if (typeof wpaa === 'function') {
            wpaa('send', 'event', {
                eventCategory: category,
                eventAction: action,
                eventLabel: label,
                eventValue: value
            });
        }
    } catch (error) {
        console.error('Analytics tracking error:', error);
    }
}

Troubleshooting

Common Issues

1. Events Not Appearing

Problem: Events are not showing up in the dashboard.

Solutions:

  • Check if the wpaa() function is available
  • Verify the events table exists
  • Check browser console for JavaScript errors
  • Ensure events are being sent with correct parameters

2. Duplicate Events

Problem: Same event is being tracked multiple times.

Solutions:

  • Use once event listeners where appropriate
  • Implement debouncing for scroll events
  • Check for multiple event listeners on the same element

3. Performance Issues

Problem: Too many events affecting site performance.

Solutions:

  • Implement event throttling
  • Use requestIdleCallback for non-critical events
  • Batch similar events together

Debug Mode

Enable debug mode to see events in the console:

// Add this to your JavaScript
window.wpaa_debug = true;

// Events will now log to console
wpaa('send', 'event', {
    eventCategory: 'Button',
    eventAction: 'Click',
    eventLabel: 'Test Button'
});

Testing Events

Use browser developer tools to test events:

// Test in browser console
wpaa('send', 'event', {
    eventCategory: 'Test',
    eventAction: 'Manual',
    eventLabel: 'Console Test'
});

Advanced Examples

Scroll Depth Tracking

let scrollMilestones = [25, 50, 75, 90, 100];
let trackedMilestones = [];

window.addEventListener('scroll', function() {
    const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100);

    scrollMilestones.forEach(milestone => {
        if (scrollPercent >= milestone && !trackedMilestones.includes(milestone)) {
            wpaa('send', 'event', {
                eventCategory: 'Engagement',
                eventAction: 'Scroll',
                eventLabel: milestone + '%'
            });
            trackedMilestones.push(milestone);
        }
    });
});

Exit Intent Tracking

let exitIntentTriggered = false;

document.addEventListener('mouseleave', function(e) {
    if (e.clientY <= 0 && !exitIntentTriggered) {
        wpaa('send', 'event', {
            eventCategory: 'Engagement',
            eventAction: 'Exit Intent',
            eventLabel: 'Mouse Left Viewport'
        });
        exitIntentTriggered = true;
    }
});

A/B Testing Integration

// Track A/B test variations
function trackABTest(testName, variation) {
    wpaa('send', 'event', {
        eventCategory: 'A/B Test',
        eventAction: 'View',
        eventLabel: testName + ' - ' + variation
    });
}

// Example usage
if (Math.random() < 0.5) {
    // Show variation A
    document.body.classList.add('variation-a');
    trackABTest('Header CTA', 'A');
} else {
    // Show variation B
    document.body.classList.add('variation-b');
    trackABTest('Header CTA', 'B');
}

This comprehensive documentation provides everything needed to implement and use Active Analytics Events effectively across different scenarios and platforms.

WooCommerce Order Tracking

Add this code to your theme’s functions.php file or create a small plugin to track WooCommerce orders as events in Active Analytics.

Option 1: Add to Theme’s functions.php (Recommended for testing)

  1. Open your theme’s functions.php file
  2. Add the code from woocommerce-order-tracking.php at the end of the file
  3. Save the file

Option 2: Create a Small Plugin (Recommended for production)

  1. Create a new file: wpaa-woocommerce-tracking.php in your wp-content/plugins/ directory
  2. Add the plugin header and the tracking code:
<?php
/**
 * Plugin Name: Active Analytics - WooCommerce Tracking
 * Description: Tracks WooCommerce orders in Active Analytics
 * Version: 1.0.0
 */

// Add the tracking code here from woocommerce-order-tracking.php
  1. Activate the plugin from the WordPress admin

What Gets Tracked

When a customer completes an order, the following information is tracked:

  • Event Category: WooCommerce
  • Event Action: Purchase
  • Event Label: Product names (first 3 products, or “Order #123” if no products)
  • Event Value: Order total (rounded to integer)

Viewing Tracked Orders

After installation, completed orders will appear in:

  1. Active AnalyticsEvents tab
  2. Look for events with:
  • Category: WooCommerce
  • Action: Purchase

Customization

The file includes a commented-out alternative function wpaa_track_woocommerce_order_detailed() that tracks:

  • Order ID
  • Payment method
  • Number of items
  • Product names

To use it:

  1. Comment out the first function
  2. Uncomment the detailed function

Track Only Specific Order Statuses

If you want to track only completed orders (not pending, processing, etc.), modify the function:

function wpaa_track_woocommerce_order( $order_id ) {
    if ( ! is_wc_endpoint_url( 'order-received' ) ) {
        return;
    }

    $order = wc_get_order( $order_id );

    if ( ! $order || $order->get_status() !== 'completed' ) {
        return;
    }

    // ... rest of the code
}

Testing

  1. Place a test order in your WooCommerce store
  2. Complete the checkout process
  3. Go to Active AnalyticsEvents
  4. Look for a new event with Category: WooCommerce and Action: Purchase

Troubleshooting

Events not appearing?

  • Make sure Active Analytics is installed and activated
  • Check that the wpaa() JavaScript function is available (it should be if Active Analytics is active)
  • Verify the code was added correctly to your functions.php or plugin file
  • Check browser console for JavaScript errors

Want to track different information?

  • Modify the eventLabel to include different order details
  • Change eventCategory or eventAction to match your reporting needs
  • Adjust eventValue to track different numeric values (e.g., item count instead of total)
    <?php
    /**
     * Active Analytics - WooCommerce Order Tracking
     * 
     * Tracks WooCommerce orders as events in Active Analytics
     * 
     * Add this code to your theme's functions.php file or create a small plugin
     */
    
    /**
     * Track WooCommerce order completion
     * 
     * This function outputs JavaScript on the WooCommerce thank you page
     * to track the order as an event in Active Analytics
     */
    function wpaa_track_woocommerce_order( $order_id ) {
        // Only track on the thank you page
        if ( ! is_wc_endpoint_url( 'order-received' ) ) {
            return;
        }
    
        // Get the order object
        $order = wc_get_order( $order_id );
        
        if ( ! $order ) {
            return;
        }
    
        // Get order details
        $order_total = $order->get_total();
        $order_currency = $order->get_currency();
        $item_count = $order->get_item_count();
        
        // Get product names (limit to first 3 for label)
        $product_names = [];
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product();
            if ( $product ) {
                $product_names[] = $product->get_name();
            }
            if ( count( $product_names ) >= 3 ) {
                break;
            }
        }
        $products_label = ! empty( $product_names ) ? implode( ', ', $product_names ) : 'Order #' . $order_id;
        if ( $item_count > 3 ) {
            $products_label .= ' (+' . ( $item_count - 3 ) . ' more)';
        }
    
        // Get payment method
        $payment_method = $order->get_payment_method_title();
    
        // Output JavaScript to track the event
        ?>
        <script type="text/javascript">
        if (typeof wpaa !== 'undefined') {
            wpaa('send', 'event', {
                eventCategory: 'WooCommerce',
                eventAction: 'Purchase',
                eventLabel: '<?php echo esc_js( $products_label ); ?>',
                eventValue: <?php echo (int) round( $order_total ); ?>
            });
        }
        </script>
        <?php
    }
    add_action( 'woocommerce_thankyou', 'wpaa_track_woocommerce_order', 10, 1 );
    
    /**
     * Alternative: Track order with more detailed information
     * 
     * Uncomment this function and comment out the one above if you want
     * more detailed tracking with order ID and payment method
     */
    /*
    function wpaa_track_woocommerce_order_detailed( $order_id ) {
        // Only track on the thank you page
        if ( ! is_wc_endpoint_url( 'order-received' ) ) {
            return;
        }
    
        // Get the order object
        $order = wc_get_order( $order_id );
        
        if ( ! $order ) {
            return;
        }
    
        // Get order details
        $order_total = $order->get_total();
        $item_count = $order->get_item_count();
        $payment_method = $order->get_payment_method_title();
        
        // Get product names (limit to first 3 for label)
        $product_names = [];
        foreach ( $order->get_items() as $item ) {
            $product = $item->get_product();
            if ( $product ) {
                $product_names[] = $product->get_name();
            }
            if ( count( $product_names ) >= 3 ) {
                break;
            }
        }
        $products_label = ! empty( $product_names ) ? implode( ', ', $product_names ) : 'Order #' . $order_id;
        if ( $item_count > 3 ) {
            $products_label .= ' (+' . ( $item_count - 3 ) . ' more)';
        }
    
        // Create detailed label with order ID and payment method
        $detailed_label = sprintf(
            'Order #%s - %s (%s items) - %s',
            $order_id,
            $products_label,
            $item_count,
            $payment_method
        );
    
        // Output JavaScript to track the event
        ?>
        <script type="text/javascript">
        if (typeof wpaa !== 'undefined') {
            wpaa('send', 'event', {
                eventCategory: 'WooCommerce',
                eventAction: 'Purchase',
                eventLabel: '<?php echo esc_js( $detailed_label ); ?>',
                eventValue: <?php echo (int) round( $order_total ); ?>
            });
        }
        </script>
        <?php
    }
    add_action( 'woocommerce_thankyou', 'wpaa_track_woocommerce_order_detailed', 10, 1 );
    */