A recurring question in the Google Tag Manager communities (e.g. product forums) is how to use an Enhanced Ecommerce dataLayer object with the Facebook pixel code? It’s a common question since running a Facebook conversion pixel on a site that also collects data from the store into Google Analytics’ Enhanced Ecommerce reports is probably a very typical scenario.

Side note: Since Google+ is about to go the way of the dodo, I’ve created an archive of the entire community which you can browse and make text searches against.

I’ve shared a tip on this before, but I think I need to be even more specific and give concrete examples how to populate the various properties of the Facebook pixel object.

For a guide on how to implement the Facebook pixel, check out Yehoshua’s amazing Facebook Pixel with Google Tag Manager guide.

X

The Simmer Newsletter

Subscribe to the Simmer newsletter to get the latest news and content from Simo Ahava into your email inbox!

Tip 95: Use the Facebook Pixel with an Enhanced Ecommerce Data Layer

The solution here is to create an API that you can pass your Enhanced Ecommerce products array to, and it will return the array all reduced and converted to the various formats required by the Facebook Pixel.

First things first, you need to create the Custom JavaScript variable.

  1. Create a new Custom JavaScript variable in the GTM UI.

  2. Name it {{EECFB API}} (or something less of an abomination, if you wish).

  3. Add the following code within:

function() {
  return function(products) {
    if (!Array.isArray(products)) {
      return;
    }
    
    var idList = products.map(function(prod) {
      return !!prod.id && prod.id.toString();
    });
    
    var totalValue = products.reduce(function(acc, cur) {
      return !!cur.price && !!cur.quantity ? acc + (cur.price * cur.quantity) : acc;
    }, 0);
    
    var totalQuantity = products.reduce(function(acc, cur) {
      return !!cur.quantity ? acc + parseInt(cur.quantity) : acc;
    }, 0);
    
    var contentsArray = products.map(function(prod) {
      return {
        id: !!prod.id ? prod.id.toString() : undefined,
        item_price: !!prod.price ? parseFloat(prod.price) : undefined,
        quantity: !!prod.quantity ? parseInt(prod.quantity) : undefined
      };
    });
    
    return {
      content_ids: idList,
      value: totalValue,
      num_items: totalQuantity,
      contents: contentsArray
    };
  };
}

This code actually returns a function, so it’s basically a wrapper for a closure, which you can then call in your other tags using a parameter.

When you invoke this API in a Custom HTML tag, for example, you need to have a variable reference to the products array at hand to pass to this API as a parameter (I’ll show you an example soon).

The API returns an object with four properties:

Property Description Sample output
content_ids Array of all the Product IDs. ['id123', 'id234', 'id345']
value The sum of all the product prices multiplied by their respective quantities. 63.55
num_items The sum of all the quantities in the array. 5
contents The products array converted to the format Facebook requires. [{id: 'id123', quantity: 2, item_price: 10.2}]

How to put it all together

Let’s take the Facebook Purchase event as an example. Here’s what you’d need to do.

First, let’s say this is what your Enhanced Ecommerce purchase object looks like:

ecommerce: {
  purchase: {
    products: {
	  actionField: {...},
	  products: [{
        id: 'shirt1', 
        name: 'T-Shirt', 
        price: '15.99', 
        quantity: 2
      },{
        id: 'pants2', 
        name: 'Pants', 
        price: '9.99', 
        quantity: 3
      }]
    }
  }
}
  1. First, create a Data Layer variable for variable name ecommerce.purchase.products and name it {{ecommerce.purchase.products}}. This is the reference to the products in your Enhanced Ecommerce purchase object.

  2. Create a Custom HTML tag that fires after your Facebook pixel has been initialized.

  3. This is what the contents might look like:

<script>
  (function() {
    // Get reference to the Enhanced Ecommerce products
	var prods = {{ecommerce.purchase.products}};
	
	// Poll the custom Facebook API with this array
	var fbObj = {{EECFB API}}(prods);
	
	// Create the FB pixel call
	if (typeof window.fbq === 'function') {
	  window.fbq('track', 'Purchase', {
        value: fbObj.value,
        content_ids: fbObj.content_ids,
        contents: fbObj.contents,
        num_items: fbObj.num_items
	  });
	}
  })();
</script>

It’s an imaginary situation - you wouldn’t typically send the Facebook Purchase event with that payload.

Anyway, what happens here is that first you fetch a reference to the products array in the Enhanced Ecommerce purchase object. Then, you call the {{EECFB API}} passing that array as the parameter. The API returns an object, which you store in the fbObj local variable.

Then, you simply access the properties of this object (listed in the table earlier in this article) in the fbq() call. That’s how you build the required pixel call with all the necessary parameters.

So, the window.fbq() method is actually called with these values:

window.fbq('track', 'Purchase', {
  value: 61.95,
  content_ids: ['shirt1', 'pants2'],
  contents: [{
    id: 'shirt1', 
    item_price: 15.99, 
    quantity: 2
  },{
    id: 'pants2', 
    item_price: 9.99, 
    quantity: 3
  }],
  num_items: 5
});

Summary

What you’re creating here is a helper function that automatically chews up your Enhanced Ecommerce products and spits out the values in a format required by the Facebook pixel.

You can freely extend the variable with other properties, and adapting it to other source object formats should be quite simple to do, too.

In any case, let me know in the comments if you think the API needs some other properties, or if you need help in extending it!