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:

Cache-safe analytics is the only frontend loader. See Cache-Safe Event Tracking.

Architecture Diagram (Conceptual)

┌─────────────────────────────────────────────────────────────┐
│                     VISITOR BROWSER                         │
│                                                             │
│  ┌─────────────────────────────────────────────┐          │
│  │   localStorage (wpd_ai_v2_* keys)            │          │
│  │   Cookies at cart/checkout (or Immediate):   │          │
│  │   - wpd_ai_session_id                        │          │
│  │   - wpd_ai_landing_page                      │          │
│  │   - wpd_ai_referral_source                   │          │
│  └─────────────────────────────────────────────┘          │
│                       │                                     │
│                       ↓                                     │
│  ┌─────────────────────────────────────────────┐          │
│  │   JavaScript:                                 │          │
│  │   wpd-ai-client.js + wpd-ai-event-tracking.js│          │
│  │   - Session / attribution in the browser      │          │
│  │   - Captures page views and 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_Event_Tracking (event processing)           │ │
│  │   - WPDAI_Session_Context (session from payload)      │ │
│  │   - WPDAI_Analytics_Scripts (enqueue + localize)      │ │
│  │   - 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)

Files: assets/js/analytics/wpd-ai-client.js and assets/js/analytics/wpd-ai-event-tracking.js

Loading: Enqueued by WPDAI_Analytics_Scripts on wp_enqueue_scripts when analytics is enabled. Handles: wpd-ai-client and wpd-ai-event-tracking.

Main objects: window.WpdAiClient (session/attribution) and WpdAiEventTracking (events)

Responsibilities:

Key features:

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:

wpdAiClientConfig = {
  session_timeout_seconds: 1800,
  attribution_timeout_seconds: 259200,
  attribution_session_only: 0,
  override_attribution_on_new_utm: 1,
  cookie_storage_mode: "checkout_only",
  cookie_domain: "",
  is_cart: false,
  is_checkout: false
}

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

2. Browser Storage & Cookies

Primary store is localStorage (keys prefixed with wpd_ai_v2_). First-party cookies are a checkout/server-side mirror. For lifecycle and privacy details, see the Session Management guide.

localStorage keys

The wpd_ai_v2_ prefix is kept for session continuity. Do not rename it.

wpd_ai_session_id (cookie)

wpd_ai_landing_page

wpd_ai_referral_source

Why 30 minutes for the session?

Session renewal logic:

// Pseudo-code (browser)
if (localStorage session_id exists AND last_activity within 30 minutes) {
  // Continue existing session
  session_id = stored_value
  refresh last_activity
} else {
  // Start new session
  session_id = "wpd" + timestamp + random
  store session_id and last_activity
  if (no landing page OR attribution expired
      OR (Session Only AND new session)
      OR (Override UTM AND new session AND URL has tracking params)) {
    reset landing page and referral
  }
}
// Cookies written on cart/checkout (Checkout Only) or immediately (Immediate)

3. Server-Side Session Management

Live class: WPDAI_Session_Context

File: includes/analytics/WPDAI_Session_Context.php

Session identity arrives on the REST payload from the browser. The server does not create analytics sessions by sending PHP Set-Cookie headers on every page view.

Responsibilities:

WPDAI_Session_Tracking remains as shared helpers: cookie domain, attribution window seconds, and Session Only. The parent WPDAI_WooCommerce_Event_Tracking still holds shared server-side event methods.

Key methods:

Session properties:

class WPDAI_Session_Context {
  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: Sessions are written when events arrive (REST) or when server-side WooCommerce hooks fire. template_redirect only sets the current object type/ID for script localization.

Execution flow:

  1. Browser sends an event (or a server-side hook fires) with session_id, landing page, and referral
  2. WPDAI_Event_Tracking builds WPDAI_Session_Context from that payload
  3. Context resolves IP, device, and persisted attribution if cookies are missing
  4. If the session exists: updates date_updated_gmt (and attribution when provided)
  5. If not: inserts a new session row

4. Event Tracking System

Class: WPDAI_Event_Tracking (extends WPDAI_WooCommerce_Event_Tracking)

File: includes/analytics/WPDAI_Event_Tracking.php

Shared server-side methods remain on the parent in includes/classes/WPDAI_Woocommerce_Event_Tracking.php.

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

Responsibilities:

REST API Endpoint:

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:

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:
  2. Referrer domain matching:
  3. Referrer analysis:

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) {
    $result = 'Direct';
  } elseif (strpos($referral_url, 'app://') !== false) {
    $result = 'App';
  } else {
    $result = 'Referral';
  }

  // 4. Facebook / Instagram in-app browsers with no other source → Social
  if ($result === 'Direct' && $this->is_in_app_social_user_agent()) {
    return 'Social';
  }

  return $result;
}

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:

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:

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:
  5. Parse query parameters from landing page
  6. Extract campaign IDs if present:
  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?

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:
  8. Link orders to sessions (if available)
  9. Return structured data for React frontend

Optimization techniques:

9. Bot Detection

Class: WPDAI_User_Agent_Classification

Purpose: Identify and filter bot traffic

Detection methods:

When bot detected:

Why filter bots?

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:

Security measures:

Performance Characteristics

Client-Side Performance

Server-Side Performance

Database Performance

Reporting Performance

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

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 30 minutes to 60 minutes
add_filter('wpd_session_timeout_seconds', function($timeout) {
  return 60 * 60; // 60 minutes
});

Debugging & Troubleshooting

Enable Debug Logging

Alpha Insights writes logs to:

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 Browser Storage

In browser dev tools (Application tab):

System Requirements

Compatibility

Technical Limitations

Next Steps