## Google Ads Order Attribution

Understanding how Alpha Insights attributes your actual WooCommerce orders to specific Google Ads campaigns is essential for accurate profit analysis and campaign optimization. This guide explains the technical details of how order attribution works for Google Ads and how to set it up correctly.

### What is Order Attribution?

Order attribution is the process of matching your WooCommerce orders to the specific Google Ads campaign that drove the customer to your store. This enables Alpha Insights to calculate true profit by campaign, accounting for actual product costs, shipping, fees, and all other expenses—not just the revenue metrics from Google's API.

#### Two Types of Data in Alpha Insights

1. Google Ads API Data (Campaign Performance Metrics)

- Synced from Google Ads API
- Shows: Ad spend, clicks, impressions, conversions tracked by Google
- Uses Google's conversion tracking and attribution
- Good for: Comparing to Google Ads interface, monitoring spend
- Limitation: Doesn't include your actual costs (COGS, shipping, fees)

2. Alpha Insights Order Attribution (Your Actual Orders)

- Matches real WooCommerce orders to campaigns
- Enables true profit calculations including all costs
- Shows which products sold from each campaign
- Tracks customer lifetime value by acquisition campaign
- More accurate for business decisions

### How Google Ads Order Attribution Works

Google Ads attribution in Alpha Insights uses two methods, with the `google_cid` parameter being the primary and most reliable method:

#### Method 1: google_cid Parameter (Primary Method) ★ REQUIRED

CRITICAL: To enable order attribution, you MUST add the `google_cid` parameter to all your Google ad URLs.

Parameter format:

    google_cid={campaignid}

How it works:

1. You manually add `google_cid={campaignid}` to your ad URLs
2. Google replaces `{campaignid}` with the actual campaign ID
3. Customer clicks ad and lands on: `https://yourstore.com/products?google_cid=987654321`
4. Alpha Insights captures the landing page with `google_cid` in first-party cookie
5. Customer completes checkout and places order
6. Alpha Insights extracts the campaign ID from `google_cid` parameter
7. Campaign ID saved directly to order: `_wpd_ai_google_campaign_id`
8. Order permanently linked to Google Ads campaign

Why this is the primary method:

- Simple and reliable—direct campaign ID extraction
- No API lookups required—immediate attribution
- Works for all Google Ads campaign types (Search, Shopping, Display, Video, Performance Max)
- No time limitations—works regardless of order age
- 100% attribution accuracy when parameter is present

Example setup:

    Original URL:
    https://yourstore.com/products

    With tracking parameter:
    https://yourstore.com/products?google_cid={campaignid}

    If URL already has parameters:
    https://yourstore.com/products?utm_source=google&google_cid={campaignid}

#### Method 2: GCLID Auto-Tagging (Supplementary Method)

GCLID (Google Click Identifier) is a unique parameter that Google automatically adds to your landing page URLs when auto-tagging is enabled. Alpha Insights can attempt to match GCLIDs to campaigns via the Google Ads API as a supplementary attribution method.

How it works:

1. Auto-tagging enabled in Google Ads
2. Google automatically appends GCLID to landing URLs: `https://yourstore.com/products?gclid=Cj0KCQiA...`
3. Alpha Insights captures landing page with GCLID
4. Background process queries Google Ads API to match GCLID to campaign ID
5. Campaign ID saved to order if match found

Important limitations of GCLID method:

- 90-day API limit: Google Ads API only provides GCLID data for the last 90 days
- API dependency: Requires active Google Ads API connection
- Rate limiting: Lookups are throttled to respect API limits
- Date-specific matching: Can fail if order date doesn't match click date
- Not guaranteed: API lookups can fail for various technical reasons

Recommendation: Always use the `google_cid` parameter as your primary attribution method. GCLID can provide supplementary attribution but should not be relied upon as the sole method.

### Required Setup: Add google_cid Parameter

CRITICAL: For accurate order attribution, you MUST add the `google_cid` parameter to all your Google ad URLs.

#### How to Add google_cid to Your Ad URLs

In Google Ads:

1. Go to your Google Ads account
2. Navigate to Campaigns
3. Click on the campaign you want to edit
4. Go to Settings
5. Expand Additional settings
6. Click Campaign URL options
7. In the Tracking template or Final URL suffix field, add:
   `google_cid={campaignid}`
8. If using Final URL suffix: `?google_cid={campaignid}`
   (use `&google_cid={campaignid}` if your URLs already have parameters)
9. Click Save

Alternative: Add to individual ads

- Edit each ad's destination URL directly
- Append `?google_cid={campaignid}` to the URL
- Example: `https://yourstore.com/products?google_cid={campaignid}`

What happens:

- Google automatically replaces `{campaignid}` with the actual campaign ID
- Every ad click includes the campaign ID in the URL
- Alpha Insights can directly attribute orders to specific campaigns

Verification:

After adding the parameter, click one of your own ads and check the URL you land on. You should see:

    https://yourstore.com/products?google_cid=1234567890

If you see the `google_cid` parameter with a numeric campaign ID, it's working correctly!

#### Optional: Enable Auto-Tagging for Supplementary GCLID Tracking

In addition to the required `google_cid` parameter, you can optionally enable auto-tagging for supplementary GCLID tracking:

1. Go to Google Ads → Settings → Account settings
2. Scroll to Tracking section
3. Check: "Tag the URL that people click through from my ad"
4. Click Save

Note: This is optional and provides backup attribution, but `google_cid` remains the primary method.

### Understanding the Attribution Process

#### The Complete Attribution Flow

1. Customer clicks Google ad
   - Auto-tagging adds GCLID to landing URL
   - Example: `yourstore.com/products?gclid=Cj0KCQiA8vOsBhCkAR...`
2. Landing page captured
   - Alpha Insights JavaScript detects landing page
   - Full URL stored in first-party cookie: `wpd_ai_landing_page`
   - Referrer stored in cookie: `wpd_ai_referral_source`
3. Customer browses and shops
   - Session tracked, cookies persist across pages
   - Customer can leave and return (within cookie lifetime)
4. Order is created at checkout
   - Landing page saved to order meta: `_wpd_ai_landing_page`
   - Referral saved to order meta: `_wpd_ai_referral_source`
   - GCLID extracted from landing page URL
5. Background: GCLID lookup (within 90 days)
   - Alpha Insights queries Google Ads API with GCLID
   - API returns campaign ID for that click
   - Campaign ID saved to order: `_wpd_ai_google_campaign_id`
   - Order now linked to specific Google Ads campaign
6. Order appears in campaign reports
   - Revenue, costs, and profit attributed to campaign
   - Product-level detail available
   - True profit calculated with COGS

#### Visual Flow Diagram (Primary Method: google_cid)

    Google Ad Click
         ↓
    Landing: yourstore.com/products?google_cid=987654321
         ↓
    Cookie Stored: wpd_ai_landing_page = "yourstore.com/products?google_cid=987654321"
         ↓
    Customer Browses & Adds to Cart
         ↓
    Order Created (#5002)
         ↓
    Order Meta Saved:
      _wpd_ai_landing_page = "yourstore.com/products?google_cid=987654321"
         ↓
    Attribution Process:
      Extract google_cid from query params → Campaign ID = "987654321"
         ↓
    Order Meta Updated:
      _wpd_ai_google_campaign_id = "987654321"
         ↓
    Report: Order #5002 attributed to Campaign 987654321

If GCLID auto-tagging also enabled (supplementary):

    Landing: yourstore.com/products?google_cid=987654321&gclid=Cj0KCQiA...
         ↓
    Primary attribution: google_cid extracted immediately
    Backup attribution: GCLID can be looked up via API if google_cid fails

#### Code Reference

Order attribution logic:

- `WPDAI_Core->save_landing_page_to_order_meta()` (lines 1312-1357)
- `WPDAI_Google_Ads_API->set_order_campaign_id_via_query_param()` (lines 676-732)
- `WPDAI_Google_Ads_API->set_order_campaign_id_via_api_last_x_days()` (lines 741-855)
- `WPDAI_Google_Ads_API->api_fetch_campaign_id_by_gclid()` (lines 1701-1738)

### Understanding Attribution Behavior

#### GCLID API Lookup Process

How GCLID-to-Campaign Matching Works:

1. Order created with GCLID in landing page
2. Alpha Insights marks order for lookup
   - Sets temporary meta: `_wpd_ai_google_api_campaign_id_check`
3. Background process queries Google API
   - Sends GCLID and order date to Google Ads API
   - API query: `SELECT campaign.id, campaign.name FROM click_view WHERE segments.date = 'YYYY-MM-DD' AND click_view.gclid = 'GCLID'`
4. Campaign ID returned and saved
   - Saves to order meta: `_wpd_ai_google_campaign_id`
   - Order now attributed to campaign

Important Limitations:

- 90-day limit: Google Ads API only provides GCLID data for the last 90 days
- Rate limiting: Lookups are throttled (0.5 second delay between requests) to respect API limits
- Batch processing: Checks up to 250 orders at a time
- Date-specific: Query must specify the exact date the click occurred (order creation date used)

What happens if GCLID lookup fails:

- Order keeps GCLID in landing page but no campaign ID assigned
- Will retry on next scheduled lookup
- After 90 days, GCLID cannot be matched via API (too old)
- Order may be categorized as "unknown" in campaign-specific reports

#### Cookie Lifetime and Session Tracking

Cookie Duration: 10 minutes by default (refreshes with activity)

What this means:

- Customer clicks ad → cookie created with landing page (including GCLID)
- Cookie refreshes every 10 minutes while browsing
- If customer leaves site and returns within 10 minutes (inactive), cookie persists
- If inactive >10 minutes, cookie expires
- Important: Once order is created, attribution is saved permanently to order meta

Example scenario:

1. Customer clicks Google ad at 2:00 PM → lands with GCLID
2. Browses products for 5 minutes
3. Leaves site at 2:05 PM
4. Returns directly (not via ad) at 2:08 PM
5. Cookie still has original GCLID landing page
6. Places order at 2:12 PM
7. Order attributed to original Google ad campaign ✓

#### Attribution Window

No Fixed Attribution Window: Unlike Google's conversion tracking (which uses 30-day or 90-day windows), Alpha Insights doesn't use time-based attribution windows.

How it works instead:

- Attribution based on GCLID or `google_cid` in landing page
- If customer's landing page contains GCLID, order is attributed to that campaign (if within 90-day API lookup window)
- There's no time limit between click and purchase from a tracking perspective
- Attribution is "last-click" based on stored landing page cookie

Practical limitation:

- Cookie lifetime limits how long attribution persists (customer must order while cookie is active or soon after)
- GCLID API lookup only works for orders within 90 days of the original click
- Most orders are attributed within hours or days of initial click

#### Retroactive Attribution

Alpha Insights can automatically process recent orders and match GCLIDs to campaigns:

Automatic Processing Methods:

1. Query Parameter Method (google_cid)

- Function: `set_order_campaign_id_via_query_param()`
- Checks: Last 30 days of orders
- Looks for: `google_cid` parameter in landing page
- Action: Extracts campaign ID, saves to order meta
- Use case: If you manually added `google_cid` to URLs

2. GCLID API Lookup Method (Primary)

- Function: `set_order_campaign_id_via_api_last_x_days()`
- Checks: Last 30-90 days of orders (configurable)
- Looks for: GCLID in landing page
- Action: Queries Google API with GCLID, gets campaign ID, saves to order
- Limit: Only works for orders <90 days old (Google API restriction)
- Throttling: 0.5 second delay between requests

When these run:

- Automatically during scheduled API sync processes
- Can be triggered manually in Alpha Insights settings
- Runs in batches to avoid overwhelming the API

#### Orders Without Campaign Attribution

An order will NOT be attributed to a specific Google Ads campaign if:

- Landing page URL doesn't contain GCLID or `google_cid`
- Auto-tagging was disabled when ad was clicked
- GCLID lookup failed (API error, order too old, etc.)
- Customer came from a source other than Google Ads
- Order was created manually in WP Admin
- Landing page cookie was missing at checkout
- GCLID was present but order is >90 days old (API won't match it)

How these orders appear in reports:

- Orders without a campaign ID are categorized as "unknown" in Google campaign reports
- They still appear in your overall store reports (Orders, Products, Customers, etc.)
- They're excluded from Google Ads campaign-specific profit calculations
- Orders with GCLID but failed lookup may show in a pending state

Technical Note: In the data warehouse code, when querying orders by Google campaign, if no `_wpd_ai_google_campaign_id` is found but a GCLID exists, the order is assigned `campaign_id = 'unknown'` and grouped separately.

### Viewing Attributed Orders

Once orders are attributed to Google Ads campaigns, you can view them in Alpha Insights reports to analyze performance and profitability.

#### Google Ads Report

The primary way to view attributed orders is through the dedicated Google Ads report:

Access: Alpha Insights → Reports → Google Ads

What you'll see:

- Campaign Overview: All Google Ads campaigns with attributed metrics
- Ad Spend: Total spend per campaign (from Google Ads API)
- Attributed Orders: Number of orders matched to each campaign via `google_cid` or GCLID
- Net Sales: Total revenue from attributed orders (including tax)
- Gross Profit: Profit from attributed orders (revenue minus costs, before ad spend)
- Net Profit: True profit (gross profit minus ad spend)
- ROAS: Return on ad spend based on actual attributed orders
- Order Count: Number of orders attributed to each campaign
- Cost Per Order: Average cost to acquire each order
- Clicks & Impressions: Campaign engagement metrics from Google API
- Conversion Rate: Percentage of clicks that resulted in orders

Report Features:

- Filter by date range to analyze specific time periods
- Sort campaigns by profit, ROAS, or spend
- View trends over time with data by date charts
- Compare multiple campaigns side-by-side
- Filter by campaign type (Search, Shopping, Display, Video, Performance Max)
- Export data for external analysis

Key Metrics:

- `campaign_order_count` - Total number of orders attributed to campaigns
- `campaign_order_revenue` - Net sales from attributed orders
- `campaign_order_profit` - Gross profit (before ad spend)
- `campaign_actual_profit` - Net profit (after ad spend)
- `campaign_revenue_roas` - Revenue ROAS based on attributed orders
- `campaign_cost_per_order` - Average acquisition cost per order

#### Individual Campaign View

Click on any campaign in the Google Ads report to see detailed attribution:

- Order List: All orders attributed to this specific campaign
- Product Breakdown: Which products were sold from this campaign
- Customer Details: New vs. returning customers from this campaign
- Profit Analysis: True profit with all costs factored in (COGS, shipping, fees)
- Performance Trends: How the campaign performed over time
- Campaign Type: Search, Shopping, Display, etc.

#### Custom Reports

You can also create custom reports to analyze Google Ads attribution:

Access: Alpha Insights → Reports → Create New Report

Select Entity: Google Campaigns

Available Data:

- `google_campaigns:campaigns` - Campaign-level metrics
- `google_campaigns:orders` - Individual attributed orders
- `google_campaigns:products` - Products sold via campaigns

Example Use Cases:

- Build a dashboard showing only profitable campaigns (filter by Net Profit > 0)
- Compare Search vs. Shopping campaign performance
- Analyze which products perform best in Google Ads
- Track customer acquisition cost by campaign type
- Compare Google Ads performance to Facebook Ads

#### Order Details (Individual Order View)

For troubleshooting or verification, you can view attribution data on individual orders:

Access: WooCommerce → Orders → [Order ID]

Alpha Insights adds an attribution panel showing:

- Traffic Source: Detected source (e.g., "Google")
- Referral Source: Referrer URL
- Landing Page: First page visited
- Query Parameters: All URL parameters including `google_cid` or `gclid`
- Google Campaign: Which campaign this order is attributed to

Example query parameters you might see:

    google_cid: 1234567890
    gclid: Cj0KCQiA8vOsBhCkARIsAGITMepH...
    utm_source: google
    utm_medium: cpc

Use this for:

- Verifying attribution is working correctly
- Troubleshooting why an order wasn't attributed
- Checking if `google_cid` parameter is present
- Manually adjusting campaign attribution if needed

#### Data Warehouse (For Developers)

The React data warehouse provides programmatic access to attributed orders:

- Entity: `google_campaigns`
- Orders Index: `google_campaigns:orders`
- Query Method: Fetches orders with `_wpd_ai_google_campaign_id` meta key OR orders with GCLID in landing page
- Grouping: Orders grouped by campaign ID for aggregation
- Unknown Orders: Orders without campaign ID are grouped as "unknown"

Available Columns: All standard order columns plus campaign-specific metrics

### Troubleshooting Attribution Issues

#### Issue: Orders Not Being Attributed

Symptom: Campaign has ad spend but no orders showing in Alpha Insights campaign reports

Possible Causes & Solutions:

1. Missing google_cid parameter in ad URLs ★ MOST COMMON
   - Check: Review your ad destination URLs in Google Ads
   - Fix: Add `?google_cid={campaignid}` to all ad URLs
   - Impact: All future clicks will include campaign ID for attribution
   - Note: Won't affect clicks that already happened before adding parameter
   - This is the #1 reason for missing attribution
2. Parameter added incorrectly
   - Check: Make sure you're using `google_cid` exactly (case-sensitive, underscore not hyphen)
   - Common mistakes: `google-cid` or `googlecid` or `gclid` or `campaign_id` won't work
   - Correct: `google_cid={campaignid}`
   - Verify: Click your own ad and check the URL includes `google_cid=` with a number
3. Landing pages don't preserve query parameters
   - Issue: Some page builders or redirects strip `google_cid` from URLs
   - Check: Click your own ad, verify `google_cid` appears in browser address bar after page loads
   - Fix: Ensure redirects use 301 or 302 and preserve query parameters
   - Technical: Check for JavaScript that manipulates URLs and removes parameters
4. Landing page tracking not working
   - Check: Look at an order in WooCommerce → Orders → Order details
   - Look for: Alpha Insights attribution panel with query parameters
   - If missing: Landing page tracking may not be functioning
   - Verify: Alpha Insights JavaScript is loaded on your site
5. Orders placed before parameter was added
   - Explanation: Attribution only works for orders where customer landed via URL with `google_cid`
   - Solution: Future orders will be attributed once parameter is in place
   - Tip: Run retroactive attribution function for last 30 days if you just added the parameter
6. Cookies blocked or cleared
   - Explanation: If customer blocks cookies or clears them before checkout, attribution is lost
   - Limitation: This affects all cookie-based tracking, no workaround
   - Impact: Generally affects <5% of orders

#### Issue: Wrong Campaign Attribution

Symptom: Order attributed to wrong Google campaign

Possible Causes:

- Customer clicked multiple ads: Last click wins (most recent GCLID)
- Cross-device tracking: Google tracks same user across devices, but Alpha Insights uses cookie-based tracking (different device = new session)
- Manual testing: Clicking your own ads repeatedly overwrites cookie with newest GCLID
- GCLID lookup date mismatch: API queried wrong date for GCLID

Manual Override: You can manually change the attributed campaign in WooCommerce → Orders → Order Details → Alpha Insights attribution panel → Select different campaign from dropdown

#### Issue: GCLID Present But No Campaign Match

Symptom: Order has GCLID in landing page but `_wpd_ai_google_campaign_id` is empty

Possible Reasons:

1. API lookup hasn't run yet
   - Lookup happens in background, may take time
   - Wait for next scheduled sync
2. API lookup failed
   - Check error logs in Alpha Insights → Settings → Debug
   - May need to retry attribution process
3. Order date doesn't match click date
   - API looks for GCLID on order creation date
   - If customer clicked days earlier, lookup may fail
   - Function attempts date with ±1 day variance (commented out in code to reduce API requests)
4. GCLID expired or invalid
   - GCLID may be malformed
   - Check that full GCLID is present in landing page URL

### Best Practices for Accurate Attribution

#### 1. Use google_cid on ALL Google Ads ★ REQUIRED

This is absolutely essential:

- Add `?google_cid={campaignid}` to every single ad you create
- Without this parameter, orders cannot be attributed to specific campaigns
- Create a checklist or SOP for your team when launching ads
- Audit existing ads and add the parameter retroactively
- This is the primary and most reliable attribution method

#### 2. Optionally Enable Auto-Tagging for Backup

For supplementary tracking:

- Enable auto-tagging in Google Ads settings
- GCLID provides backup attribution in some cases
- Not a replacement for `google_cid` due to 90-day API limit and other limitations
- Can help catch some orders that might otherwise be unattributed

Recommended setup:

    Primary: google_cid={campaignid} (REQUIRED)
    Supplementary: Auto-tagging enabled (optional backup)

#### 3. Test Your Attribution Setup

Testing steps:

1. Add `google_cid={campaignid}` to one of your ad URLs
2. Click your own ad (or use Preview mode)
3. Verify `google_cid` appears in landing page URL with a campaign ID number
4. Place a test order on your site
5. Go to WooCommerce → Orders → Your test order
6. Check Alpha Insights attribution panel
7. Verify `google_cid` appears in query parameters
8. Verify "Google Campaign" dropdown shows correct campaign
9. Check the Google Ads report to confirm order appears under that campaign

#### 4. Monitor Attribution Success Rate

Regularly check:

- How many orders have `google_cid` in landing page
- How many orders have `_wpd_ai_google_campaign_id` assigned
- Percentage of "unknown" orders in Google campaign reports

Good indicators:

- Most orders from Google Ads have `google_cid` parameter (>90%)
- Attribution rate matches parameter presence (>95%)
- Low percentage of unknown orders from Google traffic (<10%)

Red flags:

- Many orders from Google but no `google_cid` → parameter not added to ads
- Parameters present but no campaign match → tracking or extraction issue
- High unknown order percentage (>30%) → attribution not working

#### 5. Understand Data Discrepancies

Expect differences between:

- Google Ads interface (Google's conversion tracking)
- Alpha Insights API data (synced from Google)
- Alpha Insights order attribution (GCLID + actual orders)

Why they differ:

- Google may count conversions on different devices (cross-device tracking)
- Google uses view-through conversions (saw ad, didn't click)
- Alpha Insights uses click-only attribution (must have GCLID)
- Different attribution windows
- Some orders may fail GCLID lookup

Which to trust? Use Alpha Insights order attribution for business decisions—it's based on your actual orders with real costs. Use Google metrics for comparison to their reported performance.

### Alternative Tracking: UTM Parameters

#### Using Standard UTM Parameters

While not necessary with auto-tagging, you can also use UTM parameters for additional tracking:

    ?utm_source=google&utm_medium=cpc&utm_campaign={campaignid}

Benefits:

- Works with other analytics tools (Google Analytics, etc.)
- Human-readable campaign names in URLs
- Consistent with other marketing channels

Limitations:

- Doesn't enable campaign attribution in Alpha Insights (GCLID or `google_cid` required)
- Useful for traffic analysis but not order attribution

Best practice: Use auto-tagging (GCLID) for attribution, UTM parameters for traffic analysis.

### Technical Implementation Details

#### Database Schema

Order Meta Keys:

    _wpd_ai_landing_page                    (Full landing URL with GCLID/parameters)
    _wpd_ai_referral_source                 (Referrer URL, e.g. google.com)
    _wpd_ai_google_campaign_id              (Campaign ID from GCLID lookup or google_cid)
    _wpd_ai_google_api_campaign_id_check    (Temporary flag: GCLID lookup attempted)

Campaign Post Type:

    Post Type: google_ad_campaign
    Taxonomy: ad_account
    Meta Fields: _wpd_campaign_id, _wpd_campaign_name, _wpd_campaign_spend, etc.

#### Key PHP Functions

1. Save Landing Page to Order

    Method: WPDAI_Core->save_landing_page_to_order_meta($order)
    Hook: woocommerce_checkout_order_processed
    Action: Reads cookies, saves landing page and referral to order meta,
            extracts google_cid if present and saves to _wpd_ai_google_campaign_id

2. Retroactive Attribution via Query Parameter

    Method: WPDAI_Google_Ads_API->set_order_campaign_id_via_query_param($days)
    Action: Queries last X days of orders with google_cid in landing page,
            extracts campaign ID, saves to order meta
    Default: 30 days

3. GCLID Lookup via API

    Method: WPDAI_Google_Ads_API->set_order_campaign_id_via_api_last_x_days($days, $hard_refresh)
    Action: Queries orders with GCLID, looks up campaign ID via Google Ads API,
            saves campaign ID to order meta
    Default: 30 days
    Limit: 90 days (Google API restriction)
    Throttling: 0.5 second delay between requests

4. API Campaign Lookup by GCLID

    Method: WPDAI_Google_Ads_API->api_fetch_campaign_id_by_gclid($gclid, $date)
    API Query: SELECT campaign.id, campaign.name FROM click_view
               WHERE segments.date = 'YYYY-MM-DD' AND click_view.gclid = 'GCLID'
    Returns: Campaign ID or false if not found

5. Query Orders by Campaign

    Method: WPDAI_Data_Warehouse->get_google_campaign_order_data($date_from, $date_to)
    Action: Fetches orders with _wpd_ai_google_campaign_id OR orders with GCLID,
            groups by campaign ID, calculates metrics
    Returns: Array of order data indexed by campaign ID
    Note: Orders with GCLID but no campaign ID are marked as "unknown"

#### JavaScript Tracking

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

Key Functions:

- Captures landing page URL on first page load (including GCLID)
- Stores in first-party cookie: `wpd_ai_landing_page`
- Cookie refreshes on subsequent page views
- Available at checkout for order attribution
- No modification of GCLID—preserved exactly as provided by Google

#### Data Warehouse Integration

Entity: `google_campaigns`

Available Indexes:

- `campaigns` - Campaign performance metrics from Google Ads API
- `orders` - Orders attributed to campaigns via GCLID/google_cid
- `products` - Products sold via campaigns

Order Query Logic (conceptual):

    // Get orders with campaign ID
    SELECT orders WHERE _wpd_ai_google_campaign_id = 'campaign_123'

    // Get orders with GCLID (may not have campaign ID yet)
    SELECT orders WHERE _wpd_ai_landing_page LIKE '%gclid=%'

    // Combined for comprehensive reporting

### Comparing Attribution Models

#### Google Ads Conversion Tracking vs Alpha Insights Attribution

Factor | Google Ads | Alpha Insights
--- | --- | ---
Method | Conversion tracking tag | GCLID + first-party cookie + order meta
Attribution Window | 30 days (default, configurable) | No time limit (based on landing page cookie)
View-Through Conversions | Yes (optional) | No (click required)
Cross-Device Tracking | Yes (Google account-based) | No (cookie-based, single device)
Data Shown In | Google Ads interface, Alpha Insights API metrics | Alpha Insights order reports
Includes COGS | No | Yes
Product-Level Detail | Limited | Full detail (product, quantity, costs)
Best For | Comparing to Google reports, optimization in Google Ads | True profit analysis, business decisions

#### Why Numbers Differ

You'll often see different order/revenue numbers between:

- Google Ads Interface (Google's conversion tracking)
- Alpha Insights Campaign Metrics (API data from Google)
- Alpha Insights Order Attribution (GCLID/google_cid tracking)

This is normal! Each system measures differently:

- Google tracks cross-device: Customer clicks on mobile, converts on desktop → counted by Google, may not be matched by Alpha Insights (different cookies)
- Google uses view-through: Customer saw ad but didn't click, later purchased → counted by Google, not by Alpha Insights
- Alpha Insights requires click: Must have GCLID from actual ad click
- GCLID lookup can fail: Order has GCLID but API lookup fails → not attributed
- Different time frames: Google reports on click date, Alpha Insights on order date

Typical discrepancy: Google Ads may report 20-40% more conversions than Alpha Insights attributes (due to cross-device and view-through conversions).

Which to trust? Use Alpha Insights order attribution for business decisions and profit analysis. Use Google Ads metrics for campaign optimization within the Google Ads platform.

### Summary

Google Ads order attribution in Alpha Insights works by:

1. Requiring the `google_cid={campaignid}` parameter in all ad URLs (PRIMARY METHOD)
2. Capturing landing page URLs with `google_cid` when customers click ads
3. Storing landing page data in first-party cookies
4. Extracting campaign ID directly from `google_cid` parameter
5. Saving campaign ID to order meta when orders are created
6. Linking orders to campaigns for true profit reporting
7. Optionally using GCLID auto-tagging as supplementary attribution

Key Takeaways:

- google_cid parameter MUST be added to all ad URLs for attribution
- This is the primary method—simple, reliable, and has no time limitations
- Auto-tagging/GCLID is optional and provides supplementary attribution with limitations
- Without google_cid, orders cannot be reliably attributed to specific campaigns
- Attribution enables true profit tracking by campaign with all costs included

For questions about setting up attribution or troubleshooting issues, see the Google Ads Troubleshooting Guide.