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.
Alpha Insights uses a custom-built, first-party tracking system that combines:
┌─────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────┘
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:
document.ready.products .product aform submit eventsData 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"
}
Three first-party cookies are set: For complete details on cookie lifecycle, expiration, and privacy implications, see the Session Management guide.
wpd5f4dcc3b5aa7651234567890WPDAI_Session_Tracking::generate_unique_session_id()https://yourstore.com/products?utm_source=facebook&utm_campaign=springhttps://www.google.com/search?q=...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()
}
Class: WPDAI_Session_Tracking
File: includes/classes/WPDAI_Session_Tracking.php
Responsibilities:
Key methods:
setup_session_data() - Initializes all session propertiesget_set_session_id() - Retrieves or creates session IDget_set_landing_page() - Captures landing page from cookieget_set_referral_url() - Captures referrer from cookie or headersget_set_ip_address() - Captures visitor IP (with proxy support)store_session_in_db() - Inserts/updates session recordSession 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:
template_redirect hookWPDAI_Session_Tracking->store_session_in_db_hook() executesstore_session_in_db()date_updated_gmt, landing_page, referral_urlClass: 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:
/wp-json/alpha-insights/v1/woocommerce-eventsValidation checks:
event_type parameter must be presentWPDAI_User_Agent_Classification->isBot()Server-side event hooks:
woocommerce_add_to_cart - Tracks add to cart (server-side, reliable)woocommerce_order_status_changed - Tracks order completion and failureswp_login / woocommerce_customer_login - Tracks loginswp_logout - Tracks logoutsEvent 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
)
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):
fbclid present → Socialgclid present → Google Adsmc_cid present → Emailutm_medium=email → Emailutm_source=mailpoet → Email$organic_sources array → Organic$referral_url_email_sources array → Email$referral_url_ai_chat_sources array → AI Chat$social_sources array → Socialapp:// protocol → AppKey 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';
}
}
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:
Hook: woocommerce_checkout_order_processed or manual order save
Method: WPDAI_Core->save_landing_page_to_order_meta()
Process:
wpd_ai_landing_page, wpd_ai_referral_source_wpd_ai_landing_page - Full landing URL with query parameters_wpd_ai_referral_source - Referrer URLmeta_cid → Save to _wpd_ai_meta_campaign_id (Facebook)google_cid → Save to _wpd_ai_google_campaign_id (Google)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?
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:
session_idOptimization techniques:
Class: WPDAI_User_Agent_Classification
Purpose: Identify and filter bot traffic
Detection methods:
When bot detected:
is_bot property set to 1Why filter bots?
Rate limit: 60 requests per minute per IP address
For complete security and privacy details, see the Privacy & Security guide.
Implementation: WordPress transients
Process:
wpd_ai_rate_limit_{ip_hash}IP banning:
wpd_ai_ip_banned_{ip_hash}Security measures:
For tips on optimizing report performance, see Optimizing Report Performance.
// 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);
// 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);
// 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');
// 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);
// 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);
// 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);
// Change session timeout from 10 minutes to 30 minutes
add_filter('wpd_session_timeout_seconds', function($timeout) {
return 30 * 60; // 30 minutes
});
Alpha Insights writes logs to:
wp-content/uploads/wpd-logs/wpd_db_error.txt - Database errorswp-content/uploads/wpd-logs/wpd_order_update.txt - Order updatesCheck these logs if tracking isn't working.
// 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.
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
// 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
// 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.
In browser dev tools (Application tab → Cookies):
wpd_ai_session_id