## Facebook Ads Order Attribution

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

### What is Order Attribution?

Order attribution is the process of matching your WooCommerce orders to the specific Facebook advertising 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 simplified metrics from Facebook's API.

#### Two Types of Data in Alpha Insights

1. Facebook API Data (Campaign Performance Metrics)

- Synced from Facebook Marketing API
- Shows: Ad spend, impressions, clicks, purchases tracked by Facebook Pixel
- Uses Facebook's attribution model (typically 7-day click, 1-day view)
- Good for: Quick performance overview, comparing to Facebook Ads Manager
- 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 Facebook Order Attribution Works

#### The Attribution Process

Alpha Insights uses a query parameter system to track which campaign a customer came from:

1. Customer clicks your Facebook ad containing the tracking parameter
2. Landing page URL is captured and stored in a first-party cookie (`wpd_ai_landing_page`)
3. Customer browses your store (can leave and return within cookie lifetime)
4. Customer completes checkout and places an order
5. Alpha Insights saves attribution data to the order:
   - Landing page URL → `_wpd_ai_landing_page` order meta
   - Referral source → `_wpd_ai_referral_source` order meta
   - Campaign ID → `_wpd_ai_meta_campaign_id` order meta
6. Order is permanently linked to the Facebook campaign for reporting

#### Visual Flow Diagram

    Facebook Ad Click
         ↓
    Landing Page: yourstore.com/products?meta_cid=123456789
         ↓
    Cookie Stored: wpd_ai_landing_page = "yourstore.com/products?meta_cid=123456789"
         ↓
    Customer Browses (session tracked, cookie persists)
         ↓
    Order Created (#5001)
         ↓
    Order Meta Saved:
      _wpd_ai_landing_page = "yourstore.com/products?meta_cid=123456789"
      _wpd_ai_meta_campaign_id = "123456789"
         ↓
    Report: Order #5001 attributed to Campaign 123456789

### Required Setup: The meta_cid Parameter

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

#### Parameter Format

Add this to every Facebook ad destination URL:

    meta_cid={{campaign.id}}

#### How to Add the Parameter

In Facebook Ads Manager:

1. Go to your ad or ad set settings
2. Find the Website URL or Destination field
3. Add the parameter to your URL

Example URLs:

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

    With tracking parameter:
    https://yourstore.com/products?meta_cid={{campaign.id}}

    If URL already has parameters:
    https://yourstore.com/products?utm_source=facebook&meta_cid={{campaign.id}}

#### What Happens Behind the Scenes

1. Facebook automatically replaces `{{campaign.id}}` with the actual campaign ID (e.g., `23851234567890123`)
2. Your visitor lands on: `https://yourstore.com/products?meta_cid=23851234567890123`
3. Alpha Insights JavaScript captures the landing page URL
4. URL stored in cookie: `wpd_ai_landing_page`
5. At checkout, Alpha Insights extracts `meta_cid=23851234567890123` from the landing page
6. Campaign ID `23851234567890123` saved to order meta: `_wpd_ai_meta_campaign_id`

Code Reference: Attribution logic is in `WPDAI_Core->save_landing_page_to_order_meta()` (lines 1312-1357) and `WPDAI_Facebook_API->set_order_campaign_id_via_query_param()` (lines 435-491)

### Understanding Attribution Behavior

#### Cookie Lifetime and Session Tracking

Cookie Duration: 10 minutes by default

What this means:

- Customer clicks ad and lands on your store → cookie created
- Cookie refreshes every 10 minutes of activity
- If customer leaves and returns within 10 minutes (inactive), cookie persists
- If customer leaves for >10 minutes (inactive), cookie expires
- However: Once order is created, attribution is permanently saved to order meta (never expires)

Important: Orders are attributed based on first landing page from the cookie. If a customer clicks a Facebook ad, browses your site, leaves, then returns directly (without clicking an ad again), the order will still be attributed to the original Facebook campaign as long as they complete checkout within a reasonable timeframe.

#### Attribution Window

No Fixed Attribution Window: Alpha Insights doesn't use time-based attribution windows like "7-day click" or "30-day view."

How it works instead:

- Attribution is based on the `meta_cid` parameter in the landing page URL
- If the customer's landing page contains `meta_cid`, the order is attributed to that campaign
- There's no time limit between click and purchase (could be same day or weeks later)
- Attribution is "last-click" based on the stored landing page cookie

Why this matters: A customer could click your ad in January, and if they return in March and place an order (and still have the landing page data), it would be attributed to that campaign. In practice, cookies expire, so most attribution happens within days or weeks of the initial click.

#### Retroactive Attribution (Last 30 Days)

Alpha Insights can automatically check recent orders and assign campaign IDs retroactively:

Method: `set_order_campaign_id_via_query_param()`

What it does:

1. Checks the last 30 days of orders
2. Looks for orders with `meta_cid` in their landing page URL
3. Extracts the campaign ID from the query parameter
4. Saves it to `_wpd_ai_meta_campaign_id` order meta

When this runs:

- Automatically during API sync processes
- Can be triggered manually via settings

Use case: If you just added the `meta_cid` parameter to your ads, this function can go back and attribute orders from the last 30 days that have the parameter in their landing page.

#### Orders Without Campaign Attribution

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

- The landing page URL doesn't contain `meta_cid` parameter
- The `meta_cid` value is not numeric (malformed)
- The customer came from a source other than Facebook ads
- The order was created manually in WP Admin
- The landing page cookie was missing at checkout

How these orders appear in reports:

- Orders without a campaign ID are categorized as "unknown" in campaign reports
- They still appear in your overall store reports (Orders, Products, etc.)
- They're excluded from Facebook campaign-specific profit calculations

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

### Viewing Attributed Orders

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

#### Facebook Ads Report

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

Access: Alpha Insights → Reports → Facebook Ads

What you'll see:

- Campaign Overview: All Facebook campaigns with attributed metrics
- Ad Spend: Total spend per campaign (from Facebook API)
- Attributed Orders: Number of orders matched to each campaign via `meta_cid`
- 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

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

#### Individual Campaign View

Click on any campaign in the Facebook 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
- Performance Trends: How the campaign performed over time

#### Custom Reports

You can also create custom reports to analyze Facebook attribution:

Access: Alpha Insights → Reports → Create New Report

Select Entity: Facebook Campaigns

Available Data:

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

Example Use Cases:

- Build a dashboard showing only profitable campaigns (filter by Net Profit > 0)
- Compare campaign performance by month
- Analyze which products perform best in Facebook ads
- Track customer acquisition cost over time

#### 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., "Facebook")
- Referral Source: Referrer URL
- Landing Page: First page visited
- Query Parameters: All URL parameters including `meta_cid`
- Meta Campaign: Which campaign this order is attributed to

Use this for:

- Verifying attribution is working correctly
- Troubleshooting why an order wasn't attributed
- Manually adjusting campaign attribution if needed

#### Data Warehouse (For Developers)

The React data warehouse provides programmatic access to attributed orders:

- Entity: `facebook_campaigns`
- Orders Index: `facebook_campaigns:orders`
- Query Method: Fetches orders with `_wpd_ai_meta_campaign_id` meta key
- 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 meta_cid parameter in ad URLs
   - Check: Go to Facebook Ads Manager → Your Ad → Destination URL
   - Fix: Add `?meta_cid={{campaign.id}}` to all ad URLs
   - Note: Only affects new clicks after you add it (won't retroactively attribute old clicks)
2. Parameter added incorrectly
   - Check: Make sure you're using `meta_cid` exactly (case-sensitive, underscore not hyphen)
   - Common mistake: `meta-cid` or `metacid` or `fb_cid` won't work
   - Correct: `meta_cid={{campaign.id}}`
3. Landing page tracking not working
   - Check: Look at an order in WooCommerce → Orders → Order details
   - Look for: Alpha Insights attribution panel
   - If missing: Landing page tracking may not be functioning
   - Verify: Alpha Insights JavaScript is loaded on your site
4. Orders placed before parameter was added
   - Explanation: Attribution only works for orders where the customer landed via a URL with `meta_cid`
   - Solution: Future orders will be attributed once parameter is in place
   - Tip: Run the retroactive attribution function for last 30 days if you just added the parameter
5. 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
6. Customer took long path to purchase
   - Explanation: Customer clicked ad, browsed, left site, returned much later directly (not via ad)
   - If cookie expired: Order won't be attributed
   - Expected behavior: Attribution tracks initial landing, but cookies have limited lifetime

#### Issue: Wrong Campaign Attribution

Symptom: Order attributed to wrong campaign

Possible Causes:

- Customer clicked multiple ads: Last click wins (most recent `meta_cid` landing page)
- Manual testing: If you're clicking your own ads, your cookie will be overwritten each time
- Campaign ID changed: Facebook sometimes changes campaign IDs if you duplicate or restart campaigns

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

#### Issue: Attribution Data Missing from Orders

Symptom: Old orders don't have landing page or campaign attribution

Explanation:

- Attribution only works for orders placed AFTER Alpha Insights is installed
- Historical orders created before the plugin was activated won't have attribution data
- This is expected behavior—there's no way to retroactively track where customers came from before tracking was enabled

### Best Practices for Accurate Attribution

#### 1. Use meta_cid on ALL Facebook Ads

Consistency is key:

- Add `meta_cid={{campaign.id}}` to every single ad you create
- Create a checklist or SOP for your team when launching ads
- Audit existing ads and add the parameter retroactively

#### 2. Don't Mix Attribution Systems

Avoid using multiple campaign ID parameters:

- Don't use: `?meta_cid={{campaign.id}}&campaign_id={{campaign.id}}`
- Alpha Insights only looks for `meta_cid`—additional parameters won't improve tracking
- Extra parameters can make URLs messy and harder to maintain

#### 3. Test Your Attribution Setup

How to test:

1. Create a test ad with `meta_cid={{campaign.id}}`
2. Click your own ad (or use Facebook's "Preview" feature)
3. Note the campaign ID in the URL when you land
4. Place a test order on your site
5. Go to WooCommerce → Orders → Your test order
6. Check Alpha Insights attribution panel
7. Verify `meta_cid` appears in query parameters
8. Verify "Meta Campaign" dropdown shows the correct campaign

#### 4. Document Your Campaign IDs

Keep a spreadsheet tracking:

- Campaign Name
- Campaign ID (from Facebook)
- Start Date
- Destination URL with parameter

This helps troubleshoot attribution issues later.

#### 5. Monitor Unattributed Orders

Regularly check how many orders are categorized as "unknown":

- High percentage of unknown orders (>20%) indicates attribution issues
- Low percentage of unknown orders (<10%) is normal (organic traffic, direct, etc.)
- Investigate spike in unknown orders—might indicate tracking problems

### Technical Implementation Details

#### Database Schema

Order Meta Keys:

    _wpd_ai_landing_page        (Full landing URL with query params)
    _wpd_ai_referral_source     (Referrer URL, e.g. facebook.com)
    _wpd_ai_meta_campaign_id    (Extracted campaign ID from meta_cid)

Campaign Post Type:

    Post Type: facebook_campaign
    Taxonomy: ad_account
    Meta Fields: _wpd_campaign_id, _wpd_campaign_name, 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 meta_cid and saves to _wpd_ai_meta_campaign_id

2. Retroactive Attribution

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

3. Query Orders by Campaign

    Method: WPDAI_Data_Warehouse->get_facebook_campaign_order_data($date_from, $date_to)
    Action: Fetches all orders with _wpd_ai_meta_campaign_id,
            groups by campaign ID, calculates metrics
    Returns: Array of order data indexed by campaign ID

#### JavaScript Tracking

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

Key Functions:

- Captures landing page URL on first page load
- Stores in first-party cookie: `wpd_ai_landing_page`
- Cookie refreshes on subsequent page views
- Available at checkout for order attribution

#### Data Warehouse Integration

Entity: `facebook_campaigns`

Available Indexes:

- `campaigns` - Campaign performance metrics
- `orders` - Orders attributed to campaigns
- `products` - Products sold via campaigns

Query Example (conceptual):

    SELECT orders
    WHERE _wpd_ai_meta_campaign_id = '123456789'
    AND date_created BETWEEN '2024-01-01' AND '2024-01-31'
    AND order_status IN ('completed', 'processing')

### Comparing Attribution Models

#### Facebook Pixel Attribution vs Alpha Insights Attribution

Factor | Facebook Pixel | Alpha Insights
--- | --- | ---
Method | JavaScript pixel tracking | First-party cookie + order meta
Attribution Window | 7-day click, 1-day view (default) | No time limit (based on landing page)
View-Through Attribution | Yes (saw ad, didn't click, later purchased) | No (click required)
Data Shown In | Facebook Ads Manager, Alpha Insights campaign metrics | Alpha Insights order reports
Includes COGS | No | Yes
Product-Level Detail | Limited | Full detail
Best For | Comparing to Facebook reports, broad metrics | True profit analysis, business decisions

#### Why Numbers Differ

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

- Facebook Ads Manager (Pixel attribution)
- Alpha Insights Campaign Metrics (API data from Facebook)
- Alpha Insights Order Attribution (meta_cid tracking)

This is normal! Each system measures differently:

- Facebook counts view-through conversions (saw ad but didn't click)
- Alpha Insights only counts click-through (clicked ad and landed with meta_cid)
- Facebook uses probabilistic matching (may include conversions from same person on different device)
- Alpha Insights uses deterministic matching (must have exact parameter in landing URL)

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

### Summary

Facebook order attribution in Alpha Insights works by:

1. Requiring the `meta_cid={{campaign.id}}` parameter in all Facebook ad URLs
2. Capturing the landing page URL when customers click ads
3. Storing the landing page in first-party cookies
4. Saving campaign attribution to order meta when orders are created
5. Linking orders to campaigns for true profit reporting

Key Takeaway: Without the `meta_cid` parameter in your ad URLs, Alpha Insights cannot attribute orders to specific campaigns. This parameter is absolutely essential for accurate profit tracking by campaign.

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