3

I'm using Google Optimize for creating A/B tests. I'm using it in server side mode as in this guide: https://developers.google.com/optimize/devguides/experiments

That guide shows an easy way of setting which experiment is running with which variant by rendering the JS code on the server which sets the experiment id and variant id:

  // 2. Create a tracker.
  ga('create', 'UA-XXXXX-Y', 'auto');

<?php
<<<HTML
  // 3. Set the experiment ID and variation ID.
  ga('set', 'exp', '$experimentId.$variationId');
HTML;
?>
  // 4. Send a pageview hit to Google Analytics.
  ga('send', 'pageview');

However I'm using Google Tag manager and so far haven't managed to find any guide that shows how to set variables from the server with it. ga is an undefined variable so the above doesn't work.

Gnuffo1
  • 3,478
  • 11
  • 39
  • 53
  • Does this help? https://github.com/snowplow/snowplow/wiki/Integrating-javascript-tags-with-Google-Tag-Manager – Cataster Nov 11 '18 at 19:47

1 Answers1

9

Since the GTM calls the normal snippet for each tag, you can set any field the analytics snippet understands even if they are not yet automatically listed in the tag editor drop down.

For example, as a page view field: Fields to set

Then set DataLayer variable so it can be received from the external source, for example: DataLayer Variable

Leading to the fields using the variable in a finished Tag: Field using the DataLayer Variable

Now, you can set DataLayer variable in the server side that will be passed through to the tag. Since I chose a page view, it would be best to pre-fill the dataLayer before loading the GTM so they are present before the initial tags fire, for example:

<!-- Google Tag Manager -->
<?php or other backend language wrapping...
 <script>window.dataLayer = [{exp:"$experimentId.$experimentVariant"}] 
 </script>
?>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-0');</script>
<!-- End Google Tag Manager -->
lossleader
  • 13,182
  • 2
  • 31
  • 45
  • 2
    Yes that worked thanks. I had to make a slight change to the variables used as Google Optimize (Analytics experiments are deprecated) uses a different variable called "exp" instead of "expId" and "expVar" but in principle it's the same way of doing it. – Gnuffo1 Nov 12 '18 at 13:40
  • @Gnuffo1 ah, I misinterpreted why the GTM didn't recognize the exp field. I've updated the answer/screenshots for using the exp field. – lossleader Nov 12 '18 at 19:08
  • 1
    Thanks, this worked for me and is the simplest way and clearest guide I've found. – Tom Aug 07 '20 at 08:03