Woocommerce - Facebook Conversion Code Definition

Unlock seamless Facebook tracking for WooCommerce with accurate event mapping for every shopping step.

Ceyhun Enki Aksan
Ceyhun Enki Aksan Entrepreneur, Maker

Google Analytics E-commerce Events and Facebook Pixel Standard Events articles, in this post I will also cover events such as Add Payment Info, Add to Cart, Add to Wishlist, Customize Product, Page View, Purchase, Search, View Content, and Custom Events, which are commonly used in e-commerce transactions and are also associated with products added to the catalog.

Facebook Pixel
Facebook Pixel

Facebook Pixel Standard Events, WooCommerce, and E-commerce Transactions

As mentioned in the article titled Facebook Pixel, Advanced Matching and Special Cases, you can easily integrate your site’s events with Facebook’s Segment, WordPress, and WooCommerce plugins1. Using Facebook’s shared integrations2 (available for WordPress 3.0 and later versions with WooCommerce 2.6.14), you can efficiently and reliably send WooCommerce transaction events via Facebook Pixel events3.

Facebook
Facebook

You can also link your Catalog setup to Facebook Pixel for convenient management2. Alternatively, you can use the WooCommerce Conversion Tracking plugin4 5. However, third-party plugins will naturally not offer such comprehensive functionality and will require additional configuration. Therefore, it is preferable to rely on extensions provided by WooCommerce and/or Facebook.

Facebook
Facebook

After this stage, most of WooCommerce’s functions (ViewCategory (trackCustom), Search, ViewContent, AddToCart, InitiateCheckout, Purchase, Subscribe, and additionally Lead if the CF7 plugin is installed) will be directly linked to Facebook events. Additionally, Catalog and Facebook Chat features can also be made available. For more details, see the facebook-commerce-events-tracker.php file via this link. For detailed information and settings about the extension, navigate to WP-Admin > WooCommerce > Settings > Integration > Facebook and Facebook for WooCommerce. Let’s take a look at an example WooCommerce transaction and send it as a Facebook event.

add_action( 'woocommerce_thankyou', 'FBPixelTracking' );

function FBPixelTracking( $order_id ) {
$order = new WC_Order( $order_id );
$order_total = $order->get_total();
echo $order_total; // Order total
}

You can obtain the total payment amount (including product price, taxes, and shipping fees, among all payments) using $order_total and use it for the Purchase event. Evaluate this data within the Facebook Pixel snippet6.

<script>(function() {
     var _fbq = window._fbq || (window._fbq = []);
     if (!_fbq.loaded) {
       var fbds = document.createElement('script');
       fbds.async = true;
       fbds.src = '//connect.facebook.net/en_US/fbds.js';
       var s = document.getElementsByTagName('script')[0];
       s.parentNode.insertBefore(fbds, s);
       _fbq.loaded = true;
     }
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', '[Pixel-ID]', {'value':'<?php echo $order_total ?>','currency':'TRY'}]);
</script>
<noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/trev=XXXXXXXXXXXXXX&amp;cd[value]=<?php echo $order_total ?>&amp;cd[currency]=GBP&amp;noscript=1" /></noscript>

You can add the above code into your theme’s functions.php file to test it. Naturally, you should replace [Pixel-ID] with your own Pixel ID. Additionally, if the currency specified as TRY is outdated, you may need to update it accordingly. The relevant addition can be viewed on the /checkout/order-received/ page7 8 9. For more details, please refer to the WooCommerce Code Reference > Class WC_Order10 page11. So, how can we define other actions?

Sending WooCommerce Variables as Facebook Standard Events

For transmitting information about the payment steps, we must use the trackCustom function. For example, if we want to trigger an event for ‘Step1’, the structure we would use would be as follows.

fbq('trackCustom', 'Step1');

In step definitions, we don’t need to use any WooCommerce variable. However, we must create definitions for the relevant pages. For example, if we want to initiate the funnel based on the cart, we can trigger Step1 when the page URL contains /cart/. For this, you can use GTM, or alternatively, you can implement URL checks using JS and PHP code to trigger the corresponding action as an event. PHP Example

if(strpos($_SERVER['REQUEST_URI'], '/cart/') !== false){
/* operations */
}

JavaScript / jQuery Example

if(window.location.href.indexOf("/cart/") > -1) {
/* operations */
}

We can also associate details such as discount coupons, campaigns, and similar data with the trackCustom event.

fbq('trackCustom', 'ShareDiscount', {promotion: 'share_discount_20%'});

If we want to use the discount process together with the payment completion step, we can do the following:

fbq('track', 'Purchase',{
    value: 25.00,
    currency: 'TRY',
    contents: [{
        id: ['1234'],
        quantity: 1,
        item_price: 85.00
      },
      {
        id: ['4567'],
        quantity: 2,
        item_price: 15.00
      }],
    content_type: 'product',
    compared_product: 'recommended-banner-product',
    campaign_name: 'discount-banner',
    promotion: 'share_discount_20%'
  }
);

For orders (pages, popups, tabs, accordions, alert boxes, etc.), product comparisons, and similar product content that we intend to share with potential customers, we can also leverage the standard ViewContent event.

fbq('track', 'ViewContent', {
content_name: '[product-name]', // Product Name
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 25.00, // Product Price
currency: 'TRY'
});

We can also trigger the CustomizeProduct event when there are changes in product attributes (color, size, pattern, etc.).

fbq('trackCustom', 'CustomizeProduct')

For more detailed usage:

fbq('trackCustom', 'CustomizeProduct', {
color: 'red',
size: 'L'
});

Of course, I assumed the above examples represent a one-time conversion for a product or service. At the point of purchase, we can also associate the purchase outcome with additional actions such as membership enrollment or limited usage.

fbq('track', 'StartTrial', {
value: 0.50,
currency: 'TRY',
predicted_ltv: 15
});

fbq('track', 'Subscribe', {
value: 0.50,
currency: 'TRY',
predicted_ltv: 15
});

The above actions can be considered event types applicable for special cases outside of Facebook WooCommerce operations. Generally, the following events can be tracked:

fbq('track', 'AddToCart', {
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 25.00, // Product price
currency: 'TRY'
});

The data-product_sku value is passed as json_encode($content_ids) and is associated with ?add-to-cart=[product-page-id]. No event is defined during the cart view stage, /cart/. For subsequent page views, ViewContent and trackCustom events can be used. When navigating to the checkout page /checkout/, the InitiateCheckout event is triggered.

fbq('track', 'InitiateCheckout', {
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 25.00, // Product price
num_items: 1, // Number of items to be paid for
currency: 'TRY'
});

After providing billing, shipping, and order summary information, and upon order confirmation, the Purchase event is triggered.

fbq('track', 'Purchase', {
order_id: 1005, // Unique Order ID
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 25.00, // Product price,
currency: 'TRY'
});

For multiple products, usage can be structured as follows:

fbq('track', 'Purchase', {
content_type: 'product',
contents: [{
'id': '1234',
'quantity': 2,
'item_price': 10.00
},
{
'id': '4567',
'quantity': 1,
'item_price': 5.00
}],
value: 25.00,
currency: 'TRY'
});

If the plugin defines the last event as Search:

fbq('track', 'Search', {
search_string: get_search_query()
});

The events described above are directly provided by the plugin, and if the Contact Form 7 extension is installed, the Lead event is also provided. However, including additional e-commerce events such as AddPaymentInfo and AddToWishlist can be beneficial for analysis and more accurate targeting12.

fbq('track', 'AddPaymentInfo', {
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 0.50,
currency: 'TRY'
});

fbq('track', 'AddToWishlist', {
content_ids: ['1234'], // Unique Product ID
content_type: 'product', // product or product_category
value: 0.50,
currency: 'TRY'
});

Together with these additional events, you can include the plugin in your WordPress installation to quickly complete product catalog entries without requiring extra steps, and enable advertising targeting based on the purchase process and product pages. One important point to remember is that e-commerce transactions may not generate sufficient volume to support effective ad performance. In such cases, it is beneficial to reevaluate the behaviors and scenarios considered during the targeting process.

Facebook for Developers

Footnotes

  1. Link your WooCommerce account to Facebook. Facebook for Business
  2. Facebook Event Manager 2
  3. Brian Jackson. (2016). How to Set Up Conversion Tracking in WooCommerce
  4. weDevs. WooCommerce Conversion Tracking. WordPress Plugins
  5. Brian Jackson. (2016). How to Insert the Facebook Conversion Pixel in WordPress
  6. WooCommerce Code Reference. API Documentation
  7. WooCommerce Endpoints. WooCommerce Docs
  8. Custom tracking code for the thanks page. WooCommerce Docs
  9. Frontend Snippets. WooCommerce Docs
  10. WC_Order. WooCommerce Code Reference
  11. WooCommerce Code Reference
  12. [App Events Best Practices for E-Commerce/Retail App.