## Troubleshooting Website Traffic Tracking

This comprehensive troubleshooting guide helps you diagnose and fix common issues with Alpha Insights website traffic tracking. Follow the diagnostic steps for your specific problem to quickly identify and resolve issues.

General troubleshooting: For general Alpha Insights troubleshooting, see Troubleshooting Performance. This guide focuses specifically on website traffic tracking issues.

### Quick Diagnostic Checklist

Before diving into specific issues, run through this quick checklist:

- □ Analytics is enabled: Settings → General Settings → Enable WooCommerce Event Tracking = True
- □ You're not in an excluded user role
- □ Browser cookies are enabled
- □ JavaScript is enabled in browser
- □ No JavaScript errors in browser console
- □ Site is using HTTPS (recommended)
- □ No aggressive caching blocking JavaScript
- □ WordPress and plugins are up to date

### Issue 1: No Traffic Data Showing

#### Symptom

Reports show zero sessions, zero page views, or "No data available"

Quick reference: For understanding how tracking works, see the Technical Architecture guide.

#### Possible Causes & Solutions

1. Analytics is disabled

Check:

    Settings → General Settings → Alpha Analytics & Event Tracking
    Verify "Enable Woocommerce Event Tracking" = True

Solution: Enable tracking and wait a few minutes for data to appear

2. You're excluded from tracking

Check:

    Settings → General Settings → "Exclude These Roles From Tracking"
    Verify your user role is NOT in the exclusion list

Solution:

- Either remove your role from exclusions (temporarily)
- Or test with a different browser (incognito/private) while logged out
- Or create a test user with a non-excluded role

3. Date range is incorrect

Check: Report date range in date picker

Solution:

- Tracking only works from the moment it's enabled (no historical data)
- Set date range to "Today" or "Last 7 Days"
- Verify there has been actual traffic in that period

4. No actual traffic yet

Check: Realtime Dashboard for live activity

Solution:

- Visit your site yourself (in incognito mode, not logged in as admin)
- Browse several pages
- Check Realtime Dashboard within 1-2 minutes
- Should see session appear

5. JavaScript not loading

Check: Browser developer tools (F12) → Network tab → look for `wpd-alpha-insights-event-tracking.js`

Solution:

- If file not found (404): Check file exists at `wp-content/plugins/wp-davies-alpha-insights/assets/js/wpd-alpha-insights-event-tracking.js`
- If file blocked by firewall: Check server security rules
- If file not loading: Check theme/plugin conflicts (try Twenty Twenty-Three theme)
- Clear all caches (browser, plugin, server)

6. Database tables missing

Check: Via phpMyAdmin or WP-CLI

    // Check if tables exist
    SHOW TABLES LIKE 'wp_wpd_ai_%';

    // Should show:
    // wp_wpd_ai_session_data
    // wp_wpd_ai_events

Solution:

- Deactivate and reactivate Alpha Insights plugin
- This should create missing tables
- If still missing, check database user permissions

### Issue 2: Sessions Not Being Created

#### Symptom

Events might be tracked, but no sessions appear in reports

#### Diagnostic Steps

1. Check 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;

If no results: Sessions not being created at all

2. Check if cookies are set

- Open browser Developer Tools (F12)
- Go to Application tab (Chrome) or Storage tab (Firefox)
- Click Cookies → Your domain
- Look for: `wpd_ai_session_id`, `wpd_ai_landing_page`, `wpd_ai_referral_source`

If cookies missing:

- Cookies might be blocked by browser settings
- Privacy extensions may be blocking (try disabling)
- Incognito/Private mode may block third-party cookies (shouldn't affect first-party, but test)
- Server-side cookie setting might be failing (check PHP headers)

3. Check for bot detection false positive

    // Test if you're being flagged as a bot
    // Add this temporarily to your theme's functions.php
    add_action('template_redirect', function() {
      $user_agent = new WPDAI_User_Agent_Classification();
      if ($user_agent->isBot()) {
        error_log('Bot detected: ' . $_SERVER['HTTP_USER_AGENT']);
      }
    });

If you're flagged as bot:

- Check if your user agent string is unusual
- May happen with some developer tools or extensions
- Try different browser

4. Check PHP errors

    // Enable WordPress debug logging
    // In wp-config.php (temporarily):
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', false);

    // Then check: wp-content/debug.log for errors

### Issue 3: Events Not Being Tracked

#### Symptom

Sessions exist but specific events (page views, add to cart, etc.) are missing

#### Diagnostic Steps

1. Check REST API endpoint

    // Test API endpoint manually
    // Open browser console and run:
    fetch('/wp-json/alpha-insights/v1/woocommerce-events', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Referer': window.location.href
      },
      body: JSON.stringify({
        event_type: 'test_event',
        page_href: window.location.href
      })
    })
    .then(r => r.json())
    .then(data => console.log('API Response:', data))
    .catch(err => console.error('API Error:', err));

Expected response: `{"message": "1 rows were inserted into the db."}`

If error 403: Referer validation failing (check if domain matches)

If error 404: REST API not working (check permalink settings)

If error 429: Rate limit exceeded (wait 60 seconds)

2. Check JavaScript console for errors

- Open Developer Tools (F12) → Console tab
- Reload page
- Look for red error messages
- Look for mentions of `WpdAiEventTracking` or `alpha-insights`

Common JavaScript errors:

- `WpdAiEventTracking is not defined` → Script not loaded
- `jQuery is not defined` → jQuery not loaded (required)
- `wpdAlphaInsightsEventTracking is not defined` → Localized variables missing
- CORS errors → Check server configuration

3. Check Network tab for API calls

- Developer Tools (F12) → Network tab
- Filter by "XHR" or "Fetch"
- Reload page and navigate
- Look for POST requests to `/wp-json/alpha-insights/v1/woocommerce-events`

If no API calls: JavaScript not firing events

If API calls failing: Check response status and error message

4. Check for rate limiting

    // Check if your IP is rate limited
    // Run in WordPress admin or via WP-CLI:
    $ip = '192.168.1.100'; // Your IP
    $transient_key = 'wpd_ai_rate_limit_' . md5($ip);
    $count = get_transient($transient_key);
    echo "Request count: " . $count . " / 60";

    // Check if banned
    $ban_key = 'wpd_ai_ip_banned_' . md5($ip);
    $banned = get_transient($ban_key);
    echo "Banned: " . ($banned ? 'Yes' : 'No');

If rate limited: Wait 60 seconds

If banned: Wait 24 hours or delete transient manually

### Issue 4: Orders Not Attributed to Traffic Sources

#### Symptom

Orders show in WooCommerce but landing page/referrer not saved to order meta

#### Diagnostic Steps

1. Check if landing page cookie exists at time of order

- Add item to cart
- Open Developer Tools → Application → Cookies
- Verify `wpd_ai_landing_page` cookie exists
- Check its value (should be a URL)
- Proceed to checkout
- Cookie should still exist throughout checkout

If cookie missing or expires:

- Session may have expired (>10 minutes since last page load)
- Cookies may be blocked
- Checkout may be on different subdomain (cookies don't transfer)

2. Check order meta after purchase

    // Query order meta in database
    SELECT meta_key, meta_value
    FROM wp_postmeta
    WHERE post_id = [ORDER_ID]
    AND meta_key LIKE '_wpd_ai%';

    // Should show:
    // _wpd_ai_landing_page
    // _wpd_ai_referral_source
    // _wpd_ai_meta_campaign_id (if present)
    // _wpd_ai_google_campaign_id (if present)

If meta fields missing:

- Order created in admin (attribution only works for frontend orders)
- Cookie was missing at checkout
- `save_landing_page_to_order_meta()` not firing

3. Check if hook is firing

    // Add debugging temporarily
    add_action('woocommerce_checkout_order_processed', function($order_id) {
      error_log('Order processed: ' . $order_id);
      error_log('Landing page cookie: ' . $_COOKIE['wpd_ai_landing_page'] ?? 'NOT SET');
    }, 5); // Priority 5 (before Alpha Insights)

4. Test with fresh browser session

- Open incognito/private window
- Visit site with UTM parameters (e.g., `?utm_source=test&utm_campaign=debug`)
- Verify cookie is set (Developer Tools → Cookies)
- Add product to cart
- Complete checkout
- Check order meta for landing page

### Issue 5: UTM Parameters Not Showing in Reports

#### Symptom

UTM-tagged URLs used, but campaigns don't appear in Traffic Channels report

Quick reference: For UTM best practices, see the UTM Campaign Tracking guide.

#### Diagnostic Steps

1. Verify UTM parameters in URL

- Click your UTM link
- Check browser address bar
- UTM parameters should be visible: `?utm_source=...&utm_campaign=...`

If parameters missing:

- Link may be incorrect (check URL builder)
- Parameters may be stripped by link shorteners
- Social platforms may strip parameters (use platform-specific tracking)
- Redirects may lose parameters (check redirect preserves query string)

2. Check landing page cookie value

- After clicking UTM link, check Developer Tools → Cookies
- Look at `wpd_ai_landing_page` cookie value
- Should include full URL with UTM parameters

If UTMs not in cookie:

- Cookie may have been set before UTM visit (from previous session)
- Wait 10+ minutes for session to expire, then try again
- Or clear cookies and try again

3. Check database for UTM data

    // Check session landing pages
    SELECT landing_page
    FROM wp_wpd_ai_session_data
    WHERE landing_page LIKE '%utm_campaign%'
    ORDER BY date_created_gmt DESC
    LIMIT 10;

If UTMs not in database:

- Session not created
- Landing page cookie not being read correctly
- Data not being written to database

4. Check report date range

- UTM campaigns only appear if sessions exist in selected date range
- Set date range to include today or last 7 days
- Verify campaign had actual traffic

5. Check for typos in UTM parameters

- Must be: `utm_source`, `utm_medium`, `utm_campaign`
- NOT: `utm-source`, `utmsource`, `UTM_SOURCE`
- Spelling and format matter!

### Issue 6: Traffic Source Showing as "Unknown" or Incorrect

#### Symptom

Traffic categorized incorrectly (e.g., Facebook showing as "Unknown" instead of "Social")

Quick reference: For complete traffic source detection logic, see the Traffic Source Analysis guide.

#### Diagnostic Steps

1. Check referrer URL

    // Query database to see actual referrer
    SELECT referral_url, landing_page
    FROM wp_wpd_ai_session_data
    WHERE date_created_gmt > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    ORDER BY date_created_gmt DESC
    LIMIT 20;

Common issues:

- Referrer is empty → Classified as "Direct" (expected)
- Referrer is your own domain → Classified as "Direct" (expected)
- Referrer is unknown domain → Classified as "Referral" (expected)
- Social platform referrer not recognized → May need to use UTMs

2. Social platforms strip referrers

Problem: Facebook, Instagram, TikTok often don't send referrer for privacy

Solution: Always use UTM parameters for social posts

    // Instead of: https://yourstore.com/products
    // Use: https://yourstore.com/products?utm_source=facebook&utm_medium=social

3. Check traffic source classification logic

    // Test traffic source detection
    $traffic_type = new WPDAI_Traffic_Type_Detection($referral_url, $query_params);
    $source = $traffic_type->determine_traffic_source();
    echo "Traffic source: " . $source;

4. Add custom source detection

    // If platform not recognized, add via filter
    add_filter('wpd_traffic_source', function($source, $referral_url, $query_params) {
      if (strpos($referral_url, 'custom-platform.com') !== false) {
        return 'Custom Platform';
      }
      return $source;
    }, 10, 3);

### Issue 7: Data Appears Delayed or Missing

#### Symptom

Traffic happened hours ago but not yet in reports

#### Explanation

Expected behavior:

- Realtime Dashboard: Updates within 1-2 minutes
- Historical reports: May cache for 5-15 minutes
- Large date ranges: May take longer to process

#### Solutions

1. Check Realtime Dashboard first

- If data shows there, it's being tracked correctly
- Historical reports may just be cached
- Wait 15 minutes for cache to expire

2. Clear transient cache

    // Delete all report caches
    DELETE FROM wp_options
    WHERE option_name LIKE '_transient_wpd_%'
    OR option_name LIKE '_transient_timeout_wpd_%';

3. Check if data actually exists

    // Count today's sessions
    SELECT COUNT(*) as sessions_today
    FROM wp_wpd_ai_session_data
    WHERE DATE(date_created_gmt) = CURDATE();

    // Count today's events
    SELECT COUNT(*) as events_today
    FROM wp_wpd_ai_events
    WHERE DATE(date_created_gmt) = CURDATE();

### Issue 8: Page Views Not Tracking

#### Symptom

Sessions are created but page_view events missing or low count

#### Diagnostic Steps

1. Check if page view event is firing

- Open Developer Tools → Console
- Reload page
- Should see no errors
- Check Network tab for POST to `/wp-json/alpha-insights/v1/woocommerce-events`

2. Check jQuery dependency

- Alpha Insights tracking requires jQuery
- In Console, type: `jQuery` and press Enter
- Should show jQuery function, not "undefined"

If jQuery missing:

- Theme may not load jQuery properly
- Another plugin may be removing it
- Try switching to default theme temporarily

3. Check if document.ready is firing

    // Add to browser console
    jQuery(document).ready(function() {
      console.log('Document ready fired');
      console.log('WpdAiEventTracking:', typeof WpdAiEventTracking);
      console.log('Localized data:', wpdAlphaInsightsEventTracking);
    });

4. Check for JavaScript conflicts

- Disable other plugins one by one
- Switch to default theme (Twenty Twenty-Three)
- Test if page views start tracking
- Identify conflicting plugin/theme

### Issue 9: Add to Cart Events Missing

#### Symptom

Products being added to cart but add_to_cart events not recorded

#### Explanation

Add to cart is tracked server-side via `woocommerce_add_to_cart` hook for maximum reliability.

#### Diagnostic Steps

1. Verify add to cart actually works

- Add product to cart
- Check cart page - product should be there
- If product not added, WooCommerce issue (not tracking issue)

2. Check if hook is firing

    // Add debugging temporarily
    add_action('woocommerce_add_to_cart', function($cart_item_key, $product_id, $quantity) {
      error_log('Add to cart fired - Product: ' . $product_id . ', Qty: ' . $quantity);
    }, 5, 3); // Priority 5 (before Alpha Insights at 10)

3. Check event in database

    SELECT * FROM wp_wpd_ai_events
    WHERE event_type = 'add_to_cart'
    AND date_created_gmt > DATE_SUB(NOW(), INTERVAL 1 HOUR)
    ORDER BY date_created_gmt DESC;

4. Check if session exists

Add to cart requires active session (with cookie)

- If no session cookie, event may not be recorded
- Check Developer Tools → Cookies for `wpd_ai_session_id`

### Issue 10: High "Direct" Traffic (Seems Wrong)

#### Symptom

Most traffic showing as "Direct" even though you know it comes from other sources

#### Explanation

"Direct" traffic includes:

- Typed URLs
- Bookmarks
- Links with no referrer
- HTTPS → HTTP transitions (referrer lost)
- Links from mobile apps (often no referrer)
- Links from email clients (often no referrer)
- Links from messaging apps (WhatsApp, Messenger, etc.)
- Shortened URLs without UTMs (bit.ly, etc.)
- Links from PDFs or documents
- QR codes without UTMs

#### Solutions

1. Use UTM parameters everywhere

- Email marketing: ALWAYS use `utm_medium=email`
- Social posts: ALWAYS use `utm_source=facebook` etc.
- Paid ads: Use `utm_medium=cpc`
- QR codes: Add UTMs to destination URL
- Short links: Add UTMs before shortening

2. Enable auto-tagging for ads

- Facebook Ads: Use `meta_cid={{campaign.id}}` parameter
- Google Ads: Enable auto-tagging (gclid)
- These override "Direct" classification

3. Check for HTTPS issues

- If site is HTTP and visitors come from HTTPS sites, referrer may be lost
- Solution: Use HTTPS on your site

4. Accept some "Direct" is legitimate

- Returning customers often type URL directly
- Brand searches → direct visits are sign of brand strength
- 10-30% direct traffic is normal
- Over 50% may indicate dark social or missing UTMs

### Advanced Debugging Tools

#### Enable Debug Logging

    // In wp-config.php
    define('WP_DEBUG', true);
    define('WP_DEBUG_LOG', true);
    define('WP_DEBUG_DISPLAY', false);

    // Logs will be written to: wp-content/debug.log

#### Test REST API Directly

    // Via command line (curl)
    curl -X POST https://yoursite.com/wp-json/alpha-insights/v1/woocommerce-events \
      -H "Content-Type: application/json" \
      -H "Referer: https://yoursite.com" \
      -d '{
        "event_type": "test_event",
        "page_href": "https://yoursite.com/test",
        "event_quantity": 1,
        "event_value": 0
      }'

#### Check Database Directly

    // Recent sessions
    SELECT * FROM wp_wpd_ai_session_data
    ORDER BY date_created_gmt DESC LIMIT 10;

    // Recent events
    SELECT * FROM wp_wpd_ai_events
    ORDER BY date_created_gmt DESC LIMIT 10;

    // Event counts by type
    SELECT event_type, COUNT(*) as count
    FROM wp_wpd_ai_events
    WHERE date_created_gmt > DATE_SUB(NOW(), INTERVAL 24 HOUR)
    GROUP BY event_type;

#### Check PHP Error Logs

Location varies by server:

- cPanel: `public_html/error_log`
- WordPress: `wp-content/debug.log` (if debug enabled)
- System: `/var/log/apache2/error.log` or `/var/log/php-fpm/error.log`

### Performance Issues

#### Issue: Tracking Slowing Down Site

For general performance optimization, see Optimizing Report Performance and Troubleshooting Performance.

Symptoms:

- Slow page loads
- High server load
- Database performance issues

Diagnostic:

    // Check database table sizes
    SELECT
      table_name,
      ROUND((data_length + index_length) / 1024 / 1024, 2) as size_mb,
      table_rows
    FROM information_schema.tables
    WHERE table_schema = DATABASE()
    AND table_name LIKE 'wp_wpd_ai_%';

Solutions:

1. Archive old data:

       // Delete sessions older than 1 year
       DELETE FROM wp_wpd_ai_session_data
       WHERE date_created_gmt < DATE_SUB(NOW(), INTERVAL 365 DAY);

2. Optimize tables:

       OPTIMIZE TABLE wp_wpd_ai_session_data;
       OPTIMIZE TABLE wp_wpd_ai_events;

3. Add indexes (if missing):

       ALTER TABLE wp_wpd_ai_events ADD INDEX idx_event_type (event_type);
       ALTER TABLE wp_wpd_ai_events ADD INDEX idx_session_id (session_id);
       ALTER TABLE wp_wpd_ai_events ADD INDEX idx_date (date_created_gmt);

4. Reduce tracking frequency:
   - Exclude more user roles
   - Consider disabling for very high traffic sites (>100k sessions/month)

### Getting Help

Before contacting support, gather:

- WordPress version
- WooCommerce version
- Alpha Insights version
- PHP version
- Active theme and plugins
- Description of issue with steps to reproduce
- Screenshots or screen recordings
- Browser console errors (if applicable)
- Sample database queries showing the issue

Support checklist:

- □ Checked this troubleshooting guide
- □ Verified issue persists with default theme
- □ Tested with other plugins disabled
- □ Cleared all caches
- □ Checked browser console for errors
- □ Verified analytics is enabled
- □ Tested in different browser/incognito
- □ Checked database for data
- □ Reviewed documentation

### Common Misunderstandings

1. "Why doesn't my old data appear?"

- Alpha Insights only tracks from the moment it's enabled
- No retroactive tracking
- This is expected behavior

2. "Why do I have multiple sessions for same visitor?"

- Sessions expire after 10 minutes of inactivity
- Each return visit after expiration = new session
- This is correct behavior

3. "Why is my traffic not showing even though Google Analytics shows visitors?"

- Check if you're excluded from tracking (admin role)
- GA may count differently
- Bots may be filtered in Alpha Insights but not GA

4. "Why does order show different source than I expected?"

- Alpha Insights uses last-click attribution
- Order attributed to most recent session
- Customer may have visited multiple times from different sources
- Session may have expired between visits

#### Related Documentation

- Technical Architecture - Understand how tracking works
- Session Management - Learn about sessions and cookies
- Privacy & Security - Rate limiting and security
- UTM Campaign Tracking - Fix attribution issues
- Event Types Reference - Understand what events are tracked
- Website Analytics Overview - Core tracking concepts
- Traffic Source Analysis - Optimize based on sources
- General Settings - Configure tracking options
- Developer Documentation - Custom implementations