How to Pass Products Purchased as a Custom Variable [string] via Google Tag Manager?
Scenario:
You have a DoubleClick transaction tag [not items sold type] and want to pass the details of products purchased as one of the custom variables in DoubleClick. The ecommerce transaction [and products] itself is available in the dataLayer for you to use.
We want u1 to be 'product 1 | product 2 | product 3' [if 3 products are sold]. If only one product is sold in a transaction , it should read as 'product 1'.
Use dataLayer to capture products purchased as a custom variable in GTM
Step 1: We need to capture the values [array] of products entered within the ecommerce transaction DL push.
<script> window.dataLayer = window.dataLayer || [] dataLayer.push({ 'transactionId': '1234', 'transactionAffiliation': 'Acme Clothing', 'transactionTotal': 38.26, 'transactionTax': 1.29, 'transactionShipping': 5, 'transactionProducts': [{ 'sku': 'DD44', 'name': 'T-Shirt', 'category': 'Apparel', 'price': 11.99, 'quantity': 1 },{ 'sku': 'AA1243544', 'name': 'Socks', 'category': 'Apparel', 'price': 9.99, 'quantity': 2 }] }); </script>
In the above example, there are two products in the transaction, socks and t-shirt. We want to capture '0044|AA1243544' as the value in this JS variable.
Create a DL variable for transactionProducts like this:
Step 2: (The tricky one) is passing those values to a Custom JS variable. This is where I posted this on GTM Forum and once again, Simo Ahava helped with it. Let's call this variable {{CJS - productSKU}}
function() { var products = {{transactionProducts}}; var idString = ''; products.forEach(function(prod) { idString += prod.sku + '|'; }); return idString.slice(0,-1); }
How I understood this JS [thanks to our dev]: This JS uses the from the dataLayer.. It then creates another variable , idString as blank. For each products contained in the transaction, it uses the SKU field available within the array and adds the pipe symbol in between . In the end, it trims the text to remove extra spacing.
You now have this variable which can be used in your DoubleClick custom variables as {{CJS - productSKU}}.
Here's a link to the GTM Forum thread: