How to setup an A/B test on WordPress without a plugin

How to setup an A/B test on WordPress without a plugin

A/B testing is a methodology in advertising of using randomized experiments with two variants, A and B, which are the control and treatment in the controlled experiment.

I’ll show you how to setup an “A/B test” on your blog. So, let’s say for example that you have a blog with a lot of downloadable resources and you want to know which download button has a better conversion rate.

All you need is a Google Analytics account, Events tracking and a some PHP.

Place this in functions.php
NOTE: if you are using a child theme, place it in child theme’s functions.php

function wcr_ab_testing_button($download_link, $lifetime = 7) {
    $button_classes = array('green', 'red');
    $button_class = !empty($_COOKIE['ab_testing']) ? $_COOKIE['ab_testing'] : '';

    if (empty($button_class)) {
        $random = (float) rand() / (float) getrandmax();
        $button_class = $random < 0.5 ? $button_classes[0] : $button_classes[1];
        setcookie('ab_testing', $button_class, time() + 3600 * 24 * $lifetime); // by default... you keep the cookie for 7 days
    }

    return sprintf('<a href="%s" class="%s" onClick="_gaq.push([\'_trackEvent\', \'Download\', \'%s\']);">Download</a>', esc_url($download_link), esc_attr($button_class), esc_attr($button_class));
}

// place it when you want to show the button
// you must replace http://designmodo.github.io/Flat-UI/ with your download link, of course
echo wcr_ab_testing_button('http://designmodo.github.io/Flat-UI/');

After a few hours (maybe a day), you will be able to see the statistics in Google Analytics (in Content » Events).

Leave a Reply

Get our Wordpress
freebies to your inbox

DigitalOcean hosting coupon 10$ coupon

for DigitalOcean hosting.
Sammy-approved.

Get this deal