## Technical Architecture: How Website Tracking Works

This guide explains the technical implementation of Alpha Insights website tracking system. Understanding the architecture helps with troubleshooting, custom development, and advanced optimization. This is a developer-friendly deep dive into how the system works under the hood.

For non-technical users: Start with Understanding Website Analytics for a user-friendly overview. This guide is intended for developers and technical users.

### System Overview

Alpha Insights uses a custom-built, first-party tracking system that combines:

- Client-side JavaScript for event capture
- Server-side PHP for session management and validation
- REST API for asynchronous event submission
- Custom database tables for efficient data storage
- Cookie-based session management (first-party cookies)

### Architecture Diagram (Conceptual)

    ┌─────────────────────────────────────────────────────────────┐
    │                     VISITOR BROWSER                         │
    │                                                             │
    │  ┌─────────────────────────────────────────────┐          │
    │  │   Cookies (First-Party):                     │          │
    │  │   - wpd_ai_session_id                        │          │
    │  │   - wpd_ai_landing_page                      │          │
    │  │   - wpd_ai_referral_source                   │          │
    │  └─────────────────────────────────────────────┘          │
    │                       │                                     │
    │                       ↓                                     │
    │  ┌─────────────────────────────────────────────┐          │
    │  │   JavaScript: wpd-alpha-insights-            │          │
    │  │   event-tracking.js (~5KB)                   │          │
    │  │   - Captures page views                       │          │
    │  │   - Tracks product clicks                     │          │
    │  │   - Monitors form submissions                 │          │
    │  │   - Sends events to REST API                  │          │
    │  └─────────────────────────────────────────────┘          │
    └────────────────────────┬────────────────────────────────────┘
                             │ HTTP POST (JSON)
                             ↓
    ┌─────────────────────────────────────────────────────────────┐
    │                   WORDPRESS SERVER                          │
    │                                                             │
    │  ┌──────────────────────────────────────────────────────┐ │
    │  │   REST API Endpoint:                                  │ │
    │  │   /wp-json/alpha-insights/v1/woocommerce-events      │ │
    │  │   - Validates requests                                │ │
    │  │   - Checks rate limits                                │ │
    │  │   - Filters bots                                      │ │
    │  └──────────────────────────────────────────────────────┘ │
    │                       │                                     │
    │                       ↓                                     │
    │  ┌──────────────────────────────────────────────────────┐ │
    │  │   PHP Classes:                                        │ │
    │  │   - WPDAI_WooCommerce_Event_Tracking (event processing)        │ │
    │  │   - WPDAI_Session_Tracking (session management)        │ │
    │  │   - WPDAI_Traffic_Type_Detection (source classification)         │ │
    │  │   - WPDAI_User_Agent_Classification (device/bot detection)            │ │
    │  │   - WPDAI_Database_Interactor (DB operations)          │ │
    │  └──────────────────────────────────────────────────────┘ │
    │                       │                                     │
    │                       ↓                                     │
    │  ┌──────────────────────────────────────────────────────┐ │
    │  │   Database Tables:                                    │ │
    │  │   - wp_wpd_ai_session_data (session metadata)        │ │
    │  │   - wp_wpd_ai_events (individual events)             │ │
    │  └──────────────────────────────────────────────────────┘ │
    │                       │                                     │
    │                       ↓                                     │
    │  ┌──────────────────────────────────────────────────────┐ │
    │  │   WooCommerce Integration:                            │ │
    │  │   - Hook: woocommerce_checkout_order_processed       │ │
    │  │   - Saves landing_page/referral to order meta        │ │
    │  │   - Links orders to sessions                          │ │
    │  └──────────────────────────────────────────────────────┘ │
    │                       │                                     │
    │                       ↓                                     │
    │  ┌──────────────────────────────────────────────────────┐ │
    │  │   Reporting Engine:                                   │ │
    │  │   - WPDAI_Data_Warehouse                          │ │
    │  │   - Aggregates sessions + events + orders            │ │
    │  │   - Calculates metrics                                │ │
    │  │   - Generates report data                             │ │
    │  └──────────────────────────────────────────────────────┘ │
    └─────────────────────────────────────────────────────────────┘
                             │
                             ↓
    ┌─────────────────────────────────────────────────────────────┐
    │                ADMIN DASHBOARD (React)                      │
    │   - Traffic Channels Report                                │
    │   - Website Sessions Report                                │
    │   - Realtime Dashboard                                     │
    │   - Analytics Overview                                     │
    └─────────────────────────────────────────────────────────────┘

#### Component Breakdown

### 1. Client-Side Tracking (JavaScript)

File: `assets/js/wpd-alpha-insights-event-tracking.js`

Size: ~5KB (minified)

Loading: Enqueued via `wp_enqueue_scripts` hook, loads asynchronously

Main class: `WpdAiEventTracking`

Responsibilities:

- Capture page views on every page load
- Track product clicks on category/shop pages
- Monitor form submissions (excluding password fields)
- Listen for WooCommerce events (checkout_error, updated_checkout, etc.)
- Send event data to REST API endpoint

Key features:

- Automatic page view tracking: Fires on `document.ready`
- Product click detection: Uses jQuery selector `.products .product a`
- Form submission tracking: Listens to all `form submit` events
- WooCommerce events: Hooks into WC's JavaScript trigger system
- Asynchronous API calls: Uses jQuery AJAX, doesn't block page rendering

Data sent per event (JSON payload):

    {
      "page_href": "https://yourstore.com/products/t-shirt",
      "event_type": "page_view",
      "event_quantity": 1,
      "event_value": 0,
      "object_id": 123,
      "object_type": "product",
      "product_id": 123,
      "variation_id": 0,
      "additional_data": {}
    }

Localized variables available to JavaScript:

    wpdAlphaInsightsEventTracking = {
      api_endpoint: "/wp-json/alpha-insights/v1/woocommerce-events",
      current_post_id: 123,
      current_post_type: "product"
    }

### 2. Cookie Management

Three first-party cookies are set: For complete details on cookie lifecycle, expiration, and privacy implications, see the Session Management guide.

#### wpd_ai_session_id

- Purpose: Unique session identifier
- Value: MD5 hash of user agent + timestamp, prefixed with "wpd"
- Example: `wpd5f4dcc3b5aa7651234567890`
- Expiry: 10 minutes from last activity
- Renewal: Refreshed on every page load
- Path: / (site-wide)
- Generation: `WPDAI_Session_Tracking::generate_unique_session_id()`

#### wpd_ai_landing_page

- Purpose: Store first page visited (with full URL including query parameters)
- Value: Full URL of landing page
- Example: `https://yourstore.com/products?utm_source=facebook&utm_campaign=spring`
- Expiry: 10 minutes from last activity
- Set once: Only on first page of session
- Renewal: Expiry refreshed but value doesn't change
- Path: / (site-wide)

#### wpd_ai_referral_source

- Purpose: Store HTTP referrer URL
- Value: Referrer URL from HTTP headers
- Example: `https://www.google.com/search?q=...`
- Expiry: 10 minutes from last activity (but set indefinitely)
- Set once: Only on first page of session
- Filtering: Own domain referrers are ignored (set to empty)
- Path: / (site-wide)

Why 10 minutes?

- Industry standard for session timeout
- Balances data accuracy with user privacy
- Prevents abandoned browsing from inflating session counts
- Aligns with Google Analytics' default session timeout

Session renewal logic:

    // Pseudo-code
    if (cookie 'wpd_ai_session_id' exists) {
      // Continue existing session
      session_id = cookie_value
      refresh_cookie_expiry(10 minutes from now)
      update_session_end_time_in_db()
    } else {
      // Start new session
      session_id = generate_unique_id()
      set_cookie('wpd_ai_session_id', session_id, 10 minutes)
      landing_page = current_url_with_params
      set_cookie('wpd_ai_landing_page', landing_page, 10 minutes)
      referral_url = get_http_referer()
      set_cookie('wpd_ai_referral_source', referral_url, 10 minutes)
      create_session_in_db()
    }

### 3. Server-Side Session Management

Class: `WPDAI_Session_Tracking`

File: `includes/classes/WPDAI_Session_Tracking.php`

Responsibilities:

- Generate unique session IDs
- Manage session cookies
- Capture referral URLs from HTTP headers
- Detect device type, browser, OS (via WPDAI_User_Agent_Classification)
- Store/update session data in database
- Bot detection and filtering

Key methods:

- `setup_session_data()` - Initializes all session properties
- `get_set_session_id()` - Retrieves or creates session ID
- `get_set_landing_page()` - Captures landing page from cookie
- `get_set_referral_url()` - Captures referrer from cookie or headers
- `get_set_ip_address()` - Captures visitor IP (with proxy support)
- `store_session_in_db()` - Inserts/updates session record

Session properties:

    class WPDAI_Session_Tracking {
      public string $session_id = '';
      public string $ip_address = '';
      public string $landing_page = '';
      public string $referral_url = '';
      public int $user_id = 0;
      public string $date_created_gmt = '';
      public string $date_updated_gmt = '';
      public string $device_category = '';
      public string $operating_system = '';
      public string $browser = '';
      public string $device = '';
      public array $additional_data = array();
      public int $is_bot = 0;
    }

Hook used: `template_redirect` (priority 1)

Execution flow:

1. WordPress loads and fires `template_redirect` hook
2. `WPDAI_Session_Tracking->store_session_in_db_hook()` executes
3. Checks if CRON, AJAX, or admin (skip if true)
4. Checks if main query (skip if not)
5. Calls `store_session_in_db()`
6. Checks if session exists in database
7. If exists: Updates `date_updated_gmt`, `landing_page`, `referral_url`
8. If not exists: Inserts new session row

### 4. Event Tracking System

Class: `WPDAI_WooCommerce_Event_Tracking` (extends `WPDAI_Session_Tracking`)

File: `includes/classes/WPDAI_WooCommerce_Event_Tracking.php`

For complete details on all tracked events, see the Event Types Reference.

Responsibilities:

- Receive events from JavaScript via REST API
- Track server-side events (add to cart, orders)
- Validate and sanitize event data
- Apply rate limiting (60 requests/minute)
- Filter bots and bad requests
- Insert events into database

REST API Endpoint:

- URL: `/wp-json/alpha-insights/v1/woocommerce-events`
- Method: POST
- Content-Type: application/json
- Authentication: None (public endpoint, validated via referer)
- Rate Limit: 60 requests per minute per IP

Validation checks:

1. Referer check: Request must come from same domain
2. Event type required: `event_type` parameter must be present
3. Bot detection: Checked via `WPDAI_User_Agent_Classification->isBot()`
4. Rate limiting: Max 60 requests/minute (tracked in transients)
5. Bad request check: page_href must be present and from same domain
6. Tracking enabled: User role not in exclusion list
7. IP ban check: IP not banned for rate limit violation

Server-side event hooks:

- `woocommerce_add_to_cart` - Tracks add to cart (server-side, reliable)
- `woocommerce_order_status_changed` - Tracks order completion and failures
- `wp_login` / `woocommerce_customer_login` - Tracks logins
- `wp_logout` - Tracks logouts

Event data structure:

    // Database row structure
    array(
      'session_id'        => 'wpd5f4dcc3b5aa76...',
      'ip_address'        => '192.168.1.1',
      'user_id'           => 0,
      'page_href'         => 'https://yourstore.com/products/t-shirt',
      'object_type'       => 'product',
      'object_id'         => 123,
      'event_type'        => 'page_view',
      'event_quantity'    => 1,
      'event_value'       => 0.00,
      'product_id'        => 123,
      'variation_id'      => 0,
      'date_created_gmt'  => '2024-03-15 14:30:25',
      'additional_data'   => '{"form_id":"checkout"}' // JSON
    )

### 5. Traffic Source Classification

Class: `WPDAI_Traffic_Type_Detection`

File: `includes/classes/WPDAI_Traffic_Type_Detection.php`

Purpose: Categorize traffic into standardized sources. For complete source detection logic and optimization strategies, see the Traffic Source Analysis guide.

Detection process (priority order):

1. Query parameters first:
   - `fbclid` present → Social
   - `gclid` present → Google Ads
   - `mc_cid` present → Email
   - `utm_medium=email` → Email
   - `utm_source=mailpoet` → Email
2. Referrer domain matching:
   - Match against `$organic_sources` array → Organic
   - Match against `$referral_url_email_sources` array → Email
   - Match against `$referral_url_ai_chat_sources` array → AI Chat
   - Match against `$social_sources` array → Social
3. Referrer analysis:
   - Empty or null referrer → Direct
   - Own domain → Direct
   - `app://` protocol → App
   - External domain → Referral

Key method:

    public function determine_traffic_source() {
      // 1. Check query parameters (highest priority)
      $query_param_check = $this->check_query_parameters();
      if ($query_param_check) return $query_param_check;

      // 2. Check referrer matching
      if ($this->is_traffic_organic($referral_url)) return 'Organic';
      if ($this->is_traffic_paid_google($referral_url)) return 'Google Ads';
      if ($this->is_traffic_mail($referral_url)) return 'Email';
      if ($this->is_traffic_ai_chat($referral_url)) return 'AI Chat';
      if ($this->is_traffic_social($referral_url)) return 'Social';
      if ($this->is_traffic_direct($referral_url)) return 'Direct';

      // 3. Fallback checks
      if (empty($referral_url) || $referring_domain === $site_host) {
        return 'Direct';
      } elseif (strpos($referral_url, 'app://') !== false) {
        return 'App';
      } else {
        return 'Referral';
      }
    }

### 6. Database Schema

Table 1: Session Data

Table name: `wp_wpd_ai_session_data` (prefix may vary)

    CREATE TABLE wp_wpd_ai_session_data (
      id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      session_id VARCHAR(255) NOT NULL,
      ip_address VARCHAR(100),
      landing_page TEXT,
      referral_url TEXT,
      user_id BIGINT(20) UNSIGNED DEFAULT 0,
      date_created_gmt DATETIME NOT NULL,
      date_updated_gmt DATETIME NOT NULL,
      device_category VARCHAR(50),
      operating_system VARCHAR(100),
      browser VARCHAR(100),
      device VARCHAR(50),
      additional_data LONGTEXT,
      PRIMARY KEY (id),
      KEY session_id (session_id),
      KEY date_created_gmt (date_created_gmt),
      KEY user_id (user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Indexes:

- session_id: Fast lookup by session ID
- date_created_gmt: Date range queries for reporting
- user_id: User-specific queries

Table 2: Events

Table name: `wp_wpd_ai_events`

    CREATE TABLE wp_wpd_ai_events (
      id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      session_id VARCHAR(255) NOT NULL,
      ip_address VARCHAR(100),
      user_id BIGINT(20) UNSIGNED DEFAULT 0,
      page_href TEXT,
      object_type VARCHAR(50),
      object_id BIGINT(20) UNSIGNED DEFAULT 0,
      event_type VARCHAR(100) NOT NULL,
      event_quantity INT DEFAULT 1,
      event_value DECIMAL(10,2) DEFAULT 0.00,
      product_id BIGINT(20) UNSIGNED DEFAULT 0,
      variation_id BIGINT(20) UNSIGNED DEFAULT 0,
      date_created_gmt DATETIME NOT NULL,
      additional_data LONGTEXT,
      PRIMARY KEY (id),
      KEY session_id (session_id),
      KEY event_type (event_type),
      KEY date_created_gmt (date_created_gmt),
      KEY product_id (product_id),
      KEY user_id (user_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Indexes:

- session_id: Join sessions with events
- event_type: Filter by event type
- date_created_gmt: Date range queries
- product_id: Product-specific queries
- user_id: User-specific queries

### 7. Order Attribution System

Hook: `woocommerce_checkout_order_processed` or manual order save

Method: `WPDAI_Core->save_landing_page_to_order_meta()`

Process:

1. Order is created (checkout or manual in admin)
2. Check if request is from admin area (skip if yes - don't track admin orders)
3. Read cookies: `wpd_ai_landing_page`, `wpd_ai_referral_source`
4. Save to order meta:
   - `_wpd_ai_landing_page` - Full landing URL with query parameters
   - `_wpd_ai_referral_source` - Referrer URL
5. Parse query parameters from landing page
6. Extract campaign IDs if present:
   - `meta_cid` → Save to `_wpd_ai_meta_campaign_id` (Facebook)
   - `google_cid` → Save to `_wpd_ai_google_campaign_id` (Google)
7. Order now permanently linked to traffic source

Order meta fields:

    _wpd_ai_landing_page        = "https://store.com/products?utm_source=facebook&utm_campaign=spring_sale"
    _wpd_ai_referral_source     = "https://www.facebook.com/..."
    _wpd_ai_meta_campaign_id    = "123456789" (if meta_cid present)
    _wpd_ai_google_campaign_id  = "987654321" (if google_cid present)

Why permanent order meta?

- Session cookies expire after 10 minutes
- Customers may return days later to complete purchase
- Landing page stored in order ensures accurate attribution
- Historical data preserved even if session data is purged

### 8. Reporting & Data Aggregation

Class: `WPDAI_Data_Warehouse`

File: `includes/classes/WPDAI_Data_Warehouse.php`

Purpose: Aggregate raw session and event data into reportable metrics

Key method: `fetch_analytics_data()`

Process:

1. Accept filters (date range, traffic source, device, etc.)
2. Count total sessions matching filters
3. Batch query events and sessions (handles large datasets)
4. Join sessions with events via `session_id`
5. Calculate traffic source for each session
6. Extract UTM parameters from landing pages
7. Aggregate data into structures:
   - totals: Overall metrics
   - data_by_date: Time series data
   - categorized_data: Grouped by source, campaign, product, etc.
   - data_tables: Session-level and event-level details
8. Link orders to sessions (if available)
9. Return structured data for React frontend

Optimization techniques:

- Batched queries: Fetches data in chunks (default 10,000 records per batch)
- Transient caching: Results cached for 5-15 minutes
- Indexed queries: Uses database indexes for fast lookups
- Date range filtering: Limits data scope to requested period
- Lazy loading: Only loads data when report is accessed

### 9. Bot Detection

Class: `WPDAI_User_Agent_Classification`

Purpose: Identify and filter bot traffic

Detection methods:

- User agent string matching against known bot patterns
- Common bot keywords: "bot", "crawler", "spider", "scraper", etc.
- Known bot user agents: Googlebot, Bingbot, Yahoo! Slurp, etc.

When bot detected:

- `is_bot` property set to 1
- Session data collection stops early
- No database writes performed
- No events tracked
- Return early from tracking functions

Why filter bots?

- Prevents data pollution
- Accurate visitor counts
- Proper conversion rate calculations
- Reduces database size
- Improves report accuracy

### 10. Rate Limiting & Security

Rate limit: 60 requests per minute per IP address

For complete security and privacy details, see the Privacy & Security guide.

Implementation: WordPress transients

Process:

1. Capture visitor IP address
2. Check transient: `wpd_ai_rate_limit_{ip_hash}`
3. If exists: Increment counter
4. If counter > 60: Return error, optionally ban IP for 24 hours
5. If not exists: Create transient with counter = 1, expires in 60 seconds

IP banning:

- Transient key: `wpd_ai_ip_banned_{ip_hash}`
- Duration: 24 hours
- Prevents all tracking for that IP
- Automatic unban after 24 hours

Security measures:

- Referer validation (must be same domain)
- Input sanitization (all inputs sanitized before DB)
- Bot filtering (automatic exclusion)
- Rate limiting (prevents spam/DDoS)
- IP banning (blocks abusers)
- User role exclusion (admins can opt out)
- Bad request filtering (malformed data rejected)

#### Performance Characteristics

### Client-Side Performance

- JavaScript file size: ~5KB (vs 45KB+ for Google Analytics)
- Load time: < 50ms on average server
- Page blocking: None (async loading)
- DOM ready delay: ~10-20ms
- API call time: ~50-150ms (asynchronous, doesn't block rendering)

### Server-Side Performance

- Session check: 1-2ms per page load
- Database writes:
  - Session update: 1-3ms
  - Event insert: 1-2ms
- Bot detection: < 1ms
- Traffic source classification: < 1ms
- Total overhead per page: 5-10ms

### Database Performance

- Average session size: ~500 bytes
- Average event size: ~300 bytes
- Growth rate:
  - 1,000 sessions/month ≈ 2-3 MB/month
  - 10,000 sessions/month ≈ 20-30 MB/month
- Query performance:
  - Date range query: 50-200ms (indexed)
  - Session lookup: < 5ms (indexed)
  - Event count: 10-50ms (indexed)

### Reporting Performance

For tips on optimizing report performance, see Optimizing Report Performance.

- Report generation: 100ms - 5 seconds (depends on date range and data volume)
- Caching: 5-15 minute transient cache per report
- Batching: Large datasets processed in 10,000-record batches
- Frontend rendering: React-based, instant once data loaded

#### Developer Hooks & Filters

### Actions (Hooks)

    // Before order calculations (for custom processing)
    do_action('wpd_save_post_data_to_order_before_calculations', $order, $_POST);

    // After event is inserted
    do_action('wpd_event_inserted', $event_data, $rows_inserted);

    // After session is created/updated
    do_action('wpd_session_updated', $session_data);

### Filters

    // Modify session data before storage
    apply_filters('wpd_session_data_before_storage', $session_data);

    // Modify event data before insertion
    apply_filters('wpd_event_data_before_insertion', $event_data);

    // Customize traffic source detection
    apply_filters('wpd_traffic_source', $traffic_source, $referral_url, $query_params);

    // Modify bot detection result
    apply_filters('wpd_is_bot', $is_bot, $user_agent_string);

### Functions Available

    // Send event programmatically
    wpd_send_woocommerce_event($data);

    // Get traffic type
    wpd_get_traffic_type($referral_url, $query_params);

    // Check if analytics enabled
    wpd_is_analytics_enabled();

    // Fetch session data
    wpd_fetch_session_data($session_id);

    // Get order landing page
    wpd_get_order_meta_by_order_id($order_id, '_wpd_ai_landing_page');

#### Common Customizations

### 1. Custom Event Tracking

    // Track custom event from PHP
    $event_data = array(
      'event_type'     => 'custom_button_click',
      'event_quantity' => 1,
      'event_value'    => 0,
      'object_id'      => get_the_ID(),
      'object_type'    => 'page',
      'additional_data' => array('button_text' => 'Learn More')
    );
    wpd_send_woocommerce_event($event_data);

    // Track custom event from JavaScript
    var payload = {
      event_type: 'video_play',
      event_value: 0,
      additional_data: {video_id: 'intro-video'}
    };
    WpdAiEventTracking(payload);

### 2. Custom Traffic Source

    // Add custom traffic source detection
    add_filter('wpd_traffic_source', function($traffic_source, $referral_url, $query_params) {
      // Check for custom parameter
      if (isset($query_params['partner_ref'])) {
        return 'Partner Network';
      }
      return $traffic_source;
    }, 10, 3);

### 3. Exclude Custom User Roles

    // Exclude custom role from tracking (in addition to settings)
    add_filter('wpd_track_user', function($track_user, $user) {
      if ($user && $user->has_role('contractor')) {
        return false; // Don't track contractors
      }
      return $track_user;
    }, 10, 2);

### 4. Custom Session Timeout

    // Change session timeout from 10 minutes to 30 minutes
    add_filter('wpd_session_timeout_seconds', function($timeout) {
      return 30 * 60; // 30 minutes
    });

#### Debugging & Troubleshooting

### Enable Debug Logging

Alpha Insights writes logs to:

- `wp-content/uploads/wpd-logs/wpd_db_error.txt` - Database errors
- `wp-content/uploads/wpd-logs/wpd_order_update.txt` - Order updates

Check these logs if tracking isn't working.

### Check if Tracking is Active

    // PHP check
    if (wpd_is_analytics_enabled()) {
      echo "Analytics is enabled";
    } else {
      echo "Analytics is disabled";
    }

    // JavaScript check (in browser console)
    console.log(wpdAlphaInsightsEventTracking);
    // Should show object with api_endpoint, current_post_id, etc.

### Test API Endpoint

Send test request to REST API:

    // Using curl
    curl -X POST https://yourstore.com/wp-json/alpha-insights/v1/woocommerce-events \
      -H "Content-Type: application/json" \
      -H "Referer: https://yourstore.com" \
      -d '{"event_type":"test_event","page_href":"https://yourstore.com/test"}'

    // Should return 200 with success message

### Check Session Creation

    // Query database directly
    SELECT * FROM wp_wpd_ai_session_data
    WHERE date_created_gmt > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    ORDER BY date_created_gmt DESC
    LIMIT 10;

    // Should show recent sessions

### Verify Events are Recorded

    // Query database
    SELECT event_type, COUNT(*) as count
    FROM wp_wpd_ai_events
    WHERE date_created_gmt > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    GROUP BY event_type
    ORDER BY count DESC;

    // Should show page_view, product_click, etc.

### Test Cookie Creation

In browser dev tools (Application tab → Cookies):

- Look for `wpd_ai_session_id`
- Should be set with 10-minute expiry
- Refresh page, cookie should renew
- Wait 10+ minutes, cookie should expire and new session created

#### System Requirements

- WordPress: 5.6+
- PHP: 7.4+ (8.0+ recommended)
- MySQL: 5.6+ or MariaDB 10.0+
- WooCommerce: 5.0+
- Server Memory: 128 MB minimum (256 MB recommended)
- Database Space: 10 MB + (grows with traffic volume)
- Web Server: Apache 2.4+ or Nginx 1.18+
- SSL: Recommended for cookie security

#### Compatibility

- ✅ Works with page caching (Batcache, WP Super Cache, W3 Total Cache)
- ✅ Works with CDNs (CloudFlare, StackPath, BunnyCDN)
- ✅ Works with HPOS (High-Performance Order Storage)
- ✅ Works with multisite (each site tracked separately)
- ✅ Works with multilingual plugins (WPML, Polylang)
- ✅ Works with most themes and page builders
- ⚠️ May conflict with aggressive privacy plugins that block all cookies
- ⚠️ May need configuration with Varnish or server-side caching

#### Technical Limitations

- Session timeout: 10 minutes fixed (can be filtered)
- Attribution model: Last-click (session that created order)
- Cross-device tracking: Limited (relies on cookies, not cross-device)
- Cross-domain tracking: Not supported (single domain only)
- Historical data: Only tracks from enablement forward (no retroactive tracking)
- Bot detection: User agent based (not AI-powered)
- Offline conversions: Not tracked (online orders only)
- App tracking: Limited to web app tracking

#### Next Steps

- Read Event Types Reference for complete event list
- Review Session Management for cookie and attribution details
- Check Privacy & Security for GDPR compliance
- See Troubleshooting Guide for common issues
- Review Developer Documentation for hooks and filters
- Learn about Creating Custom Reports to build traffic reports
- Understand General Settings to configure tracking