Meta Pixel Event Tracking | OpsBlu Docs

Meta Pixel Event Tracking

Implement comprehensive Meta Pixel event tracking for OSCommerce ecommerce stores

Overview

Meta Pixel standard events enable Facebook and Instagram to:

  • Optimize ad delivery - Show ads to users most likely to convert
  • Track conversions - Measure ROI of ad campaigns
  • Build audiences - Create retargeting and lookalike audiences
  • Generate reports - Analyze customer journey and behavior

Standard Events

Meta Pixel supports these standard events for ecommerce:

  • ViewContent - Product page view
  • AddToCart - Item added to cart
  • AddToWishlist - Item added to wishlist
  • InitiateCheckout - Checkout started
  • AddPaymentInfo - Payment information entered
  • Purchase - Transaction completed
  • Search - Site search performed
  • Lead - Contact form submission
  • CompleteRegistration - Account created

ViewContent Event

Track product page views.

File: catalog/product_info.php

<?php
// After product information is loaded
if (tep_not_null($product_info)) {
  // Get category
  $category_query = tep_db_query("
    SELECT cd.categories_name
    FROM " . TABLE_CATEGORIES_DESCRIPTION . " cd
    INNER JOIN " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c ON cd.categories_id = p2c.categories_id
    WHERE p2c.products_id = '" . (int)$product_info['products_id'] . "'
    AND cd.language_id = '" . (int)$languages_id . "'
    LIMIT 1
  ");
  $category = tep_db_fetch_array($category_query);

  // Calculate price
  $special_price = tep_get_products_special_price($product_info['products_id']);
  $final_price = $special_price ? $special_price : $product_info['products_price'];
?>
<script>
fbq('track', 'ViewContent', {
  content_ids: ['<?php echo $product_info['products_id']; ?>'],
  content_type: 'product',
  content_name: '<?php echo addslashes($product_info['products_name']); ?>',
  content_category: '<?php echo $category ? addslashes($category['categories_name']) : ''; ?>',
  value: <?php echo $final_price; ?>,
  currency: '<?php echo $_SESSION['currency']; ?>'
});
</script>
<?php
}
?>

AddToCart Event

Track when items are added to cart.

Method 1: Form Submission

File: catalog/product_info.php

<form name="cart_quantity" action="shopping_cart.php" method="post" trackAddToCart()">
  <input type="hidden" name="products_id" value="<?php echo $product_info['products_id']; ?>">
  <input type="text" name="cart_quantity" value="1" id="cart_qty">
  <button type="submit">Add to Cart</button>
</form>

<script>
function trackAddToCart() {
  var quantity = parseInt(document.getElementById('cart_qty').value) || 1;
  var productPrice = <?php echo $final_price; ?>;

  fbq('track', 'AddToCart', {
    content_ids: ['<?php echo $product_info['products_id']; ?>'],
    content_name: '<?php echo addslashes($product_info['products_name']); ?>',
    content_type: 'product',
    value: productPrice * quantity,
    currency: '<?php echo $_SESSION['currency']; ?>'
  });

  return true; // Allow form submission
}
</script>

Method 2: AJAX Add to Cart

File: catalog/product_info.php or custom JS

<script>
function addToCartAjax(productId, productName, productPrice) {
  var quantity = parseInt($('#cart_qty').val()) || 1;

  $.ajax({
    url: 'shopping_cart.php',
    method: 'POST',
    data: {
      action: 'add_product',
      products_id: productId,
      cart_quantity: quantity
    },
    success: function(response) {
      // Track successful add
      fbq('track', 'AddToCart', {
        content_ids: [productId],
        content_name: productName,
        content_type: 'product',
        value: productPrice * quantity,
        currency: '<?php echo $_SESSION['currency']; ?>'
      });

      // Update cart display
      updateCart(response);
    }
  });
}
</script>

Method 3: Quick Add from Listing

File: Product listing pages

<button echo $product['products_id']; ?>', '<?php echo addslashes($product['products_name']); ?>', <?php echo $product['products_price']; ?>)">
  Quick Add
</button>

<script>
function quickAdd(id, name, price) {
  fbq('track', 'AddToCart', {
    content_ids: [id],
    content_name: name,
    content_type: 'product',
    value: price,
    currency: '<?php echo $_SESSION['currency']; ?>'
  });

  // Redirect to cart
  window.location.href = 'shopping_cart.php?action=add_product&products_id=' + id;
}
</script>

AddToWishlist Event

Track wishlist additions (if your store has wishlist functionality).

File: catalog/wishlist.php or custom wishlist code

<?php
// After item added to wishlist
if (isset($_GET['action']) && $_GET['action'] == 'add_wishlist') {
  $products_id = (int)$_GET['products_id'];

  $product_query = tep_db_query("
    SELECT pd.products_name, p.products_price
    FROM " . TABLE_PRODUCTS . " p
    INNER JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON p.products_id = pd.products_id
    WHERE p.products_id = '" . $products_id . "'
    AND pd.language_id = '" . (int)$languages_id . "'
  ");
  $product = tep_db_fetch_array($product_query);
?>
<script>
fbq('track', 'AddToWishlist', {
  content_ids: ['<?php echo $products_id; ?>'],
  content_name: '<?php echo addslashes($product['products_name']); ?>',
  content_type: 'product',
  value: <?php echo $product['products_price']; ?>,
  currency: '<?php echo $_SESSION['currency']; ?>'
});
</script>
<?php
}
?>

InitiateCheckout Event

Track when checkout process begins.

File: catalog/checkout_shipping.php (first checkout page)

<?php
// On checkout page load
if (isset($_SESSION['cart']) && $_SESSION['cart']->count_contents() > 0) {
  $products = $_SESSION['cart']->get_products();

  // Get cart total
  $cart_total = 0;
  $content_ids = array();

  foreach ($products as $product) {
    $cart_total += $product['final_price'] * $product['quantity'];
    $content_ids[] = $product['id'];
  }
?>
<script>
fbq('track', 'InitiateCheckout', {
  content_ids: <?php echo json_encode($content_ids); ?>,
  content_type: 'product',
  value: <?php echo $cart_total; ?>,
  currency: '<?php echo $_SESSION['currency']; ?>',
  num_items: <?php echo $_SESSION['cart']->count_contents(); ?>
});
</script>
<?php
}
?>

AddPaymentInfo Event

Track when payment method is selected.

File: catalog/checkout_payment.php

<?php
// Get cart total for tracking
$cart_total = 0;
$content_ids = array();

if (isset($_SESSION['cart'])) {
  $products = $_SESSION['cart']->get_products();
  foreach ($products as $product) {
    $cart_total += $product['final_price'] * $product['quantity'];
    $content_ids[] = $product['id'];
  }
}
?>

<script>
// Track when payment form is submitted
document.querySelector('form[name="checkout_payment"]').addEventListener('submit', function() {
  var paymentMethod = document.querySelector('input[name="payment"]:checked');

  if (paymentMethod) {
    fbq('track', 'AddPaymentInfo', {
      content_ids: <?php echo json_encode($content_ids); ?>,
      content_type: 'product',
      value: <?php echo $cart_total; ?>,
      currency: '<?php echo $_SESSION['currency']; ?>'
    });
  }
});
</script>

Purchase Event

The most critical event for conversion tracking.

File: catalog/checkout_process.php

Store purchase data in session after order is created:

<?php
// After order insertion ($insert_id contains order_id)
if ($insert_id) {
  // Get order details
  $order_query = tep_db_query("SELECT * FROM " . TABLE_ORDERS . " WHERE orders_id = '" . (int)$insert_id . "'");
  $order = tep_db_fetch_array($order_query);

  // Get order products
  $products_query = tep_db_query("SELECT * FROM " . TABLE_ORDERS_PRODUCTS . " WHERE orders_id = '" . (int)$insert_id . "'");

  $content_ids = array();
  $content_names = array();

  while ($product = tep_db_fetch_array($products_query)) {
    $content_ids[] = $product['products_id'];
    $content_names[] = $product['products_name'];
  }

  // Store for success page
  $_SESSION['fb_purchase'] = array(
    'transaction_id' => $insert_id,
    'value' => $order['order_total'],
    'currency' => $order['currency'],
    'content_ids' => $content_ids,
    'content_names' => $content_names,
    'num_items' => count($content_ids)
  );
}
?>

File: catalog/checkout_success.php

Track on success page:

<?php
// Retrieve purchase data
if (isset($_SESSION['fb_purchase'])) {
  $purchase = $_SESSION['fb_purchase'];
?>
<script>
fbq('track', 'Purchase', {
  content_ids: <?php echo json_encode($purchase['content_ids']); ?>,
  content_type: 'product',
  value: <?php echo $purchase['value']; ?>,
  currency: '<?php echo $purchase['currency']; ?>',
  num_items: <?php echo $purchase['num_items']; ?>
});
</script>
<?php
  // Clear to prevent duplicate tracking
  unset($_SESSION['fb_purchase']);
}
?>

Prevent Duplicate Purchases

Add duplicate protection:

<?php
// Check if already tracked
if (isset($_SESSION['fb_tracked_orders'])) {
  $tracked = $_SESSION['fb_tracked_orders'];
} else {
  $tracked = array();
}

if (isset($_SESSION['fb_purchase']) && !in_array($_SESSION['fb_purchase']['transaction_id'], $tracked)) {
  $purchase = $_SESSION['fb_purchase'];
?>
<script>
fbq('track', 'Purchase', {
  content_ids: <?php echo json_encode($purchase['content_ids']); ?>,
  content_type: 'product',
  value: <?php echo $purchase['value']; ?>,
  currency: '<?php echo $purchase['currency']; ?>',
  num_items: <?php echo $purchase['num_items']; ?>
});
</script>
<?php
  // Mark as tracked
  $tracked[] = $purchase['transaction_id'];
  $_SESSION['fb_tracked_orders'] = $tracked;
  unset($_SESSION['fb_purchase']);
}
?>

Search Event

Track site searches.

File: catalog/advanced_search_result.php

<?php
if (isset($_GET['keywords'])) {
  $search_term = tep_output_string($_GET['keywords']);
?>
<script>
fbq('track', 'Search', {
  search_string: '<?php echo addslashes($search_term); ?>'
});
</script>
<?php
}
?>

Lead Event

Track contact form submissions.

File: catalog/contact_us.php

<?php
// After form successfully submitted
if ($email_sent) {
?>
<script>
fbq('track', 'Lead', {
  content_name: 'Contact Form',
  content_category: 'Customer Support'
});
</script>
<?php
}
?>

CompleteRegistration Event

Track new account creation.

File: catalog/create_account_success.php

<script>
fbq('track', 'CompleteRegistration', {
  content_name: 'Account Registration',
  status: 'success'
});
</script>

Custom Events

Create custom events for unique interactions.

Newsletter Signup

File: catalog/newsletter.php

<?php
if ($subscription_successful) {
?>
<script>
fbq('trackCustom', 'NewsletterSignup', {
  source: 'footer',
  timestamp: '<?php echo time(); ?>'
});
</script>
<?php
}
?>

Product Review

File: catalog/product_reviews_write.php

<?php
if ($review_submitted) {
?>
<script>
fbq('trackCustom', 'ProductReview', {
  product_id: '<?php echo $products_id; ?>',
  rating: <?php echo (int)$_POST['rating']; ?>
});
</script>
<?php
}
?>

Coupon Applied

File: catalog/shopping_cart.php

<?php
if (isset($_SESSION['cc_id'])) {
  $coupon_code = $_SESSION['cc_id'];
?>
<script>
fbq('trackCustom', 'CouponApplied', {
  coupon: '<?php echo addslashes($coupon_code); ?>'
});
</script>
<?php
}
?>

Dynamic Ads

For dynamic product ads, use proper content_ids format.

Product Catalog Format

fbq('track', 'ViewContent', {
  content_ids: ['SKU123'],        // Use SKU if in catalog
  content_type: 'product',
  content_name: 'Product Name',
  value: 29.99,
  currency: 'USD'
});

Multiple Products

fbq('track', 'AddToCart', {
  content_ids: ['SKU123', 'SKU456', 'SKU789'],
  content_type: 'product',
  value: 149.95,
  currency: 'USD'
});

Event Parameters Reference

Required Parameters

fbq('track', 'Purchase', {
  value: 49.99,           // Number - total transaction value
  currency: 'USD'         // String - 3-letter ISO code
});
fbq('track', 'ViewContent', {
  content_ids: ['123'],          // Array - product IDs
  content_type: 'product',       // String - product or product_group
  content_name: 'Product Name',  // String
  content_category: 'Category',  // String
  value: 29.99,                  // Number
  currency: 'USD'                // String
});

Optional Parameters

fbq('track', 'Purchase', {
  // ... required/recommended params
  num_items: 3,                  // Number - quantity of items
  predicted_ltv: 149.99,         // Number - predicted lifetime value
  status: 'completed'            // String - order status
});

Testing Events

Method 1: Meta Pixel Helper

  1. Install Meta Pixel Helper
  2. Visit pages and trigger events
  3. Extension shows events fired with parameters

Method 2: Test Events Tool

Events Manager > Test Events > Test browser events

Events appear instantly with full parameter details.

Method 3: Browser Console

// Monitor fbq calls
window.fbq = new Proxy(window.fbq, {
  apply: function(target, thisArg, args) {
    console.log('fbq:', args);
    return target.apply(thisArg, args);
  }
});

Method 4: Events Manager

Events Manager > Data Sources > Your Pixel > Events

Shows events received (20-minute delay).

Common Issues

Events Not Firing

Problem: Pixel Helper shows no events

Solutions:

  1. Check fbq is defined: typeof fbq === 'function'
  2. Verify event syntax is correct
  3. Check for JavaScript errors
  4. Ensure Pixel base code loads first

Wrong Event Values

Problem: Value parameter incorrect

Solutions:

// BAD - String value
value: '$49.99'

// GOOD - Number value
value: 49.99

// BAD - Formatted number
value: 1,299.99

// GOOD - Unformatted number
value: 1299.99

Duplicate Events

Problem: Same event fires twice

Solutions:

  1. Check for multiple tracking codes
  2. Implement deduplication logic
  3. Use event_id for server/client deduplication

Missing Parameters

Problem: content_ids empty or undefined

Solutions:

// Always validate data exists
<?php
$product_id = isset($product_info['products_id']) ? $product_info['products_id'] : '';
?>
<script>
<?php if ($product_id): ?>
fbq('track', 'ViewContent', {
  content_ids: ['<?php echo $product_id; ?>'],
  // ...
});
<?php endif; ?>
</script>

Best Practices

1. Use Standard Events

Prefer standard events over custom for better optimization.

2. Include Value & Currency

Always include value and currency for conversion events.

3. Use Proper content_ids

Match product IDs to those in your Facebook Product Catalog.

4. Test Before Launch

Use Test Events tool to verify all events before running ads.

5. Implement Deduplication

Use event_id to prevent counting same conversion twice:

// Client-side
fbq('track', 'Purchase', {
  value: 49.99,
  currency: 'USD'
}, {
  eventID: 'order_12345'
});

// Server-side (Conversions API)
// Send same event_id to deduplicate

Event Optimization

Value Optimization

Meta can optimize for purchases with specific values:

fbq('track', 'Purchase', {
  value: 149.99,        // Optimize for high-value purchases
  currency: 'USD'
});

Catalog Optimization

Match content_ids to product catalog for dynamic ads:

fbq('track', 'ViewContent', {
  content_ids: ['SKU_12345'],  // Must match catalog item_id
  content_type: 'product'
});

Next Steps

Additional Resources