Sometimes you may want to store additional information in Google Analytics for E-commerce transactions. This post will detail one way of doing so for a ‘similar products’ feature, however, this solution can be adapted for other types of information.

To summarise the solution in a single line: store the information in a cookie and at check out submit the information in the items’ category parameter.

Product Page

Let’s start with some simple HTML for the similar products feature.

<h3>Similar Products</h3>

<ul id="similar-products">
	<li><a href="product/094584305" data-sku="094584305">Blue Jacket</a></li>
	<li><a href="product/082756246" data-sku="082756246">Red Jacket</a></li>
	<li><a href="product/043062684" data-sku="043062684">Blue Sweater</a></li>
</ul>

If a user clicks on one of these product links we need to store this action until the check out and compare it against the purchased items. We are going to use cookies as the storage mechanism.

Mozilla has a succinct cookie utility http://developer.mozilla.org/en-US/docs/Web/API/document.cookie but unfortunately, they added a GPL licence to it at some point making it unsuitable for some projects.

No matter, a quick search on Github reveals this to be currently the most popular JavaScript cookie library https://github.com/ScottHamper/Cookies and it comes with an MIT licence. It creates a global Cookie object.

Here is the JavaScript to store this action in a cookie.

function addProductToSimilarProductsStore(event) {
	var productId = event.target.getAttribute('data-sku'),
		existingCookieValue = Cookies.get('similarProducts'),
		newCookieValue;
	
	if (typeof existingCookieValue === 'undefined') {
		Cookies.set('similarProducts', productId, { expires: '01/01/2016' });
    } else {
    	if (Cookies.get('similarProducts').indexOf(productId) === -1) {
        	newCookieValue = existingCookieValue + ',' + productId;
           	Cookies.set('similarProducts', newCookieValue, { expires: '01/01/2016' });
       }
    }
}

document.getElementById('similar-products').addEventListener('click', function(event) {
	addProductToSimilarProductsStore(event)
}, false);

The code does the following:

  • captures the click, (addEventListener polyfill for IE8)
  • gets the product ID from the data-sku attribute, if you do not have an attribute like this you will probably need an extra step to parse the id from the href
  • if a cookie called similarProducts does not exist, creates one and adds the product ID to it.
  • if a similarProducts cookie does exist, checks the product ID is not already stored and if not adds it to the cookie with a comma character as a separator.

Checkout Page

The final step is to send the E-commerce data to Google Analytics after ordering.

(transaction data that is unimportant for this example such as price, revenue, tax… have been omitted to make the solution simpler).

First, we load in the e-commerce plugin and have the order data in a format we can use to send as a transaction to Google Analytics.

ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');
ga('require', 'ecommerce', 'ecommerce.js');

var products = [
{
id: '059175924',
title: 'Blue-T-shirt',
category: 'Clothing',
quantity: '1'
},
{
id: '094584305',
title: 'Blue-Jacket',
category: 'Clothing',
quantity: '1'
},
{
id: '043062684',
title: 'Blue-Sweater',
category: 'Clothing',
quantity: '1'
}
];

getSimilarProductIds() checks if a similarProducts cookie exists and if so returns an array of the values.

function getSimilarProductIds(){
  var similarProducts = Cookies.get('similarProducts');

    if (typeof similarProducts !== 'undefined') {
    return similarProducts.split(',');
    } else {
      return false;
    }
}

updateItemIfSimilarProduct() loops through each product/item object, created from the actual customer order, and for each one then loops through the similarProductIds array to see if the current product objects’ id can be found in the similarProductIds array. If it does it amends the product objects’ category to add ‘Similar Product’ to the end.

function updateItemIfSimilarProduct() {
    for (var i = 0, productsLen = products.length; i < productsLen; i++) {
        for (var k = 0, sPLen = similarProductIds.length; k < sPLen; k++) {
            if (products[i].id === similarProductIds[k]) {
                products[i].category = products[i].category + ', Similar Product';
            }
        }
    }
}

(If not supporting Internet Explorer 8 or lower, or you have other JS libraries loaded on this page, you could re-write that function with some of the extra array methods available for a cleaner solution).

Finally, the code that uses those two methods along with setting up the E-commerce transaction, looping through the products array to create E-commerce items, and then sending the transaction.

var similarProductIds = getSimilarProductIds(),
    totalProducts = products.length,
    item = 0;

if (similarProductIds !== false) {
    updateItemIfSimilarProduct();
    Cookies.expire('similarProducts')
}

ga('ecommerce:addTransaction', {'id': '21012014-1834-3245'});

while (item < totalProducts) {
        ga('ecommerce:addItem', {
          'id': '21012014-1834-7365',                     
          'name': products[item].title,    
          'sku': products[item].id,                 
          'category': products[item].category,              
          'quantity': products[item].quantity                   
        });
    item++;
}

ga('ecommerce:send');

Solution in full can be seen by viewing the source here

The downside to this solution, seen in the screenshot below, is if you wanted to see how many items from a category like Clothing were sold you would now need to do a search. The positive is you can combine this metadata with Segments, Custom Reports… to gain insight from Google Analytics data that is not available in database/server-side tools.

Google Analytics interface screenshot

Another example of where this solution was useful was for a job website. Treating job applications as ’transactions’, The Marketing team asked for metadata such as the client name, client type (e.g. agency or direct), promoted job… that they could then combine with other parts of Google Analytics to assist with the marketing strategy.