·

photo credit: Surveillance2 via photopin (license)

How to use datalayer variables in Google Tag Manager

So today I was asked the question to add the transaction ID and order amount of a Magento order to some specific tracking pixel on the checkout page of Magento. However, the client already was using Google Tag Manager to put this pixel on the checkout page, and I already had a dataLayer present in Magento. So how did I tie these two together?

Variables in Google Tag Manager

When you’re using Google Tag manager, you probably noticed the ‘variables’-tab on the left side of the page before:

Screen Shot 2015-05-26 at 16.21.56
On the bottom of this page you have the possibility to add your own, custom variables: User-Defined variables. With these variables you can create snippets that can be used as placeholders in other tags. For example: you can create a snippet called ‘hello’, and display the content of that snippet by including it on another tag by using {{hello}} .
But the best part is: you can use JavaScript to create the content of this snippet as well!

Create a Custom JavaScript variable

Back to our case: so we have a datalayer with all kind of information, and Google Tag Manager allows us to use JavaScript to display this data. The first thing we need to do is create a new variable of the type ‘Custom Javascript’. You are now presented with a large text area where you can simply start typing your JavaScript. Since our dataLayer from Magento is a global accessible variable, we can simply use:

For our transaction total amount, and:

To get our transaction ID. Of course, you can use as much as you like from the dataLayer, but in this example I’ll limit this to these two. I named them ‘Datalayer – Total’ and ‘Datalayer – Transaction ID’.

Put it in a tag

Now I’ve created these 2 variables, I can create them anywhere in Google Tag Manager. In the case I was working on, where I had to create a tracking pixel on the checkout/success page, I included a custom HTML snippet on this page like this:

In above example, the parameters {{Datalayer – Transaction ID}}  and {{Datalayer – Total}}  are automagically replaced by Google Tag Manager with the values fetched from the dataLayer. So yeah, it’s actually quite simple.

Visitors give this article an average rating of 5.0 out of 5.

How would you rate this article?

2 thoughts on “How to use datalayer variables in Google Tag Manager”

  1. carlos says:

    Hi Giel,
    Nice and quick tip!
    I’m not sure when exactly you posted your solution, but now it’s possible to get data layer variables directly from the GTM without use a custom javascript. Just choose the option “Data Layer Variable” when creating a new variable.

    I hope it can help.

  2. Really helpfull tip for GTM. Im starting to roll in this platform and this is very handy. Thanks Giel!

Leave a Reply