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:

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:

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:

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

wpd_ai_landing_page

wpd_ai_referral_source

Why 10 minutes?

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:

Key methods:

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:

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) {
    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:

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 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:

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):

System Requirements

Compatibility

Technical Limitations

Next Steps