Recently I come across A/B testing, to see which algorithm is most effective to trigger user clicks.

Here I use Google Optimize, setup via
Google Tag Manager to do the job.

1. Setup Google Optimize

I assume you have Google Analytics ready. Let’s create an experiment, and select the type A/B test.

Google Optimize setup

Create a variant, put in whatever name you like. Then set Page Targeting to
URL equals SERVER_SIDE. Link up with GA & set the objective

2. Setup in GTM

1. Create Data Layer variables

GTM data layer variables

Create 2 variables: experiment ID & variant

GTM data layer variables - experiment ID

GTM data layer variables - variant

2. Create new tag for Google Analytics (if you don’t have)

GTM tag - google analytics

  • Check the option Enable overriding settings in this tag
  • Add 2 variables to Fields to Set
  • Set the trigger to All Page

GTM tag - google analytics

The fields to set is allow you to define which experiment & which variant to run.

3. Coding

In server side (I use PHP here), randomly choose a variant, and select the algorithm to use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
$exp_id = 'xxxxxxxxxx';

// get the cookie value form GA, to make sure the experiment result always consistent
$ga_cookie = $_COOKIE['_ga'];
$sess_key = 'exp-' . $ga_cookie;
$exp_var = $_SESSION[$sess_key];
if ($exp_var === null) {
$exp_var = rand(0, 1);
$_SESSION[$sess_key] = $exp_var;
}

if ($exp_var == 1) {
// if variant 1, which algorithm to use
} else {
// by default, which algorithm to use
}

In front end, trigger the experiment manually, by setting the dataLayer variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
<!-- Google Tag Manager -->
var dataLayer = [];
function gtag() {dataLayer.push(arguments)}

dataLayer.push({
'gaExpId': '<?php echo $expid; ?>',
'gaExpVar': '<?php echo $exp_var; ?>',
});

(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-1234567');
</script>

Note that the dataLayer.push must before the GTM script.

If you have any questions, please ask here.


P/S: If you’re looking for other way of do A/B testing, this article might be for you
Flexible A/B Testing with AWS Lambda@Edge

References: