
When it comes to measuring data, there are often times when, for whatever reason, we need to dig much deeper into where that data comes from and have it sent by email.
This usually reaches us and we can store it in an external database or connect it to some kind of contact and/or customer manager to keep better track of the contact’s original source.
To do what I’m describing, I followed the steps in this post:
The article is in English and I removed the part about tracking the form page and the conversion, but I added Client ID tracking, which can be more useful.
These changes are reflected in the second step of this article
Installation
I’m going to explain the installation for those who don’t understand the code, and I’ll tweak the code slightly so that you can extract:
- Client ID: in principle you won’t have any problems here as long as the analytics script runs
- Campaign: only with utm_campaign.
- Medium: always, except for direct traffic. It can be changed with utm_medium.
- Source: always, except for direct traffic. It can be changed with utm_source.
- Content: only with utm_content.
- Term: only with utm_keyword.
We create a custom cookie
Copy the following script and save it in a new tag in Google Tag Manager of the Custom HTML type, named «GA Custom Cookie Script«, which will fire on all pages.
Before saving, you’ll need to replace «align.ly» in the code with your domain name, like this: «queseo.es».
<script>
//
// .ooooo. ooo. .oo. .ooooo. oooo d8b
// d88' `88b `888P"Y88b d88' `88b `888""8P
// 888888888 88888 888 888 888 888 888
// 888 88888 888 888 888 888 888
// `"88888" o888o o888o `Y8bod8P' d888b
//
/***************************************************************************************************
Author: Allaedin Ezzedin
Company: E-Nor Inc
Last Updated: October 14, 2014
/***************************************************************************************************/
/******************* Google Analytics Legacy Tracking Code *******************/
// List all top-level domains that are belong to your organization for cross domain tracking
var domains = ["align.ly"];
var source, medium, term, content,campaign, session_count, pageview_count;
var hostname = document.location.hostname;
hostname = hostname.match(/(([^.\/]+\.[^.\/]{2,3}\.[^.\/]{2})|(([^.\/]+\.)[^.\/]{2,4}))(\/.*)?$/)[1];
hostname = hostname.toLowerCase();
var _gaq = _gaq || [];
// DON'T UPDATE THE GA ACCOUNT ID - Your site should be tracked using Universal Analytics outside this JavaScript code
_gaq.push(['sfga._setAccount', 'UA-XXXYYYZZZ-1']);
_gaq.push(['sfga._setDomainName', hostname]);
_gaq.push(['sfga._setAllowLinker', true]);
_gaq.push(['sfga._trackPageview']);
_gaq.push(function(){get_campaign_info();});
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
/******************* Set Up Cross Domain Tracking *******************/
var arr = document.getElementsByTagName("a");
for(i=0; i < arr.length; i++)
{
var tmp = arr[i].getAttribute("onclick");
var doname ="";
try
{
doname = arr[i].hostname.match(/(([^.\/]+\.[^.\/]{2,3}\.[^.\/]{2})|(([^.\/]+\.)[^.\/]{2,4}))(\/.*)?$/)[1];
doname = doname.toLowerCase();
}
catch(err)
{
doname = arr[i].href;
}
if (tmp != null)
{
tmp = String(tmp);
if (tmp.indexOf('_gasf.push') > -1)
continue;
}
for (var j = 0; j < domains.length; j++)
{
//Auto-Linker
if ( doname != hostname && doname.indexOf(domains[j]) != -1 && doname.indexOf("mailto:") == -1)
{
arr[i].setAttribute("onclick",""+((tmp != null) ? tmp + '; ' : '')+"_gaq.push(['sfga._link', '"+arr[i].href+"']); return false;");
}
}
}
/******************* Set Up Cross Domain Tracking *******************/
//This function extracts the "_utma", "_utmb", "_utmc" and "_utmz" strings from the cookies set by Google Analytics
//This function was originally written by the Google Analytics team (urchin.js)
function get_campaign_info()
{
var utma = get_utm_value(document.cookie, '__utma=', ';');
var utmb = get_utm_value(document.cookie, '__utmb=', ';');
var utmc = get_utm_value(document.cookie, '__utmc=', ';');
var utmz = get_utm_value(document.cookie, '__utmz=', ';');
source = get_utm_value(utmz, 'utmcsr=', '|');
medium = get_utm_value(utmz, 'utmcmd=', '|');
term = get_utm_value(utmz, 'utmctr=', '|');
content = get_utm_value(utmz, 'utmcct=', '|');
campaign = get_utm_value(utmz, 'utmccn=', '|');
gclid = get_utm_value(utmz, 'utmgclid=', '|');
session_count = get_session_count(utma);
pageview_count = get_pageview_count(utmb, utmc);
if (gclid !="-") {
source = 'google';
medium = 'cpc';
}
}
function get_utm_value(l,n,s)
{
if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
var i, j, k, utm="-";
i=l.indexOf(n);
k=n.indexOf("=")+1;
if (i > -1)
{
j=l.indexOf(s,i);
if (j < 0)
{
j=l.length;
}
utm=l.substring((i+k),j);
}
return utm;
}
//This function extracts the "Count of Sessions" value from the _utma cookie
function get_session_count(str)
{
var i, vc='-';
if (str != '-') {
i = str.lastIndexOf(".");
i++;
vc = str.substring(i);
}
return vc;
}
//This function extracts the "Count of Pageviews" value from the _utmb cookie
function get_pageview_count(utmb,utmc)
{
var i, j, pc='-';
if(utmb != '-' && utmc != '-'){
utmc=utmc+'.';
i=utmc.length;
j=utmb.indexOf(".", i);
pc=utmb.substring(i,j);
}
return pc;
}
</script>We pull data from the cookie to insert it into the form
The next step is very similar to the previous one, although this code does include slight changes from the original, as I mentioned at the beginning.
Once again, copy the script you’ll see below and save it in a new tag in Google Tag Manager of the Custom HTML type, named «GA Cookie Extraction Script«, also with the all pages trigger.
Here too we’ll need to replace «align.ly» with our domain name, which in my case would be «queseo.es».
<script>
// 2 second delay to let Google Analytics cookies load
setTimeout(function () {
// Split the GA cookie
var GATrafficSource = (function () {
var pairs = (/(?:^|; )__utmz=([^;]*)/.exec(document.cookie) || []).slice(1).pop().split('.').slice(4).join('.').split('|');
var vals = {};
for (var i = 0; i < pairs.length; i++) {
var temp = pairs[i].split('=');
vals[temp[0]] = temp[1];
}
return {
'utm_source': (vals.utmgclid) ? "google" : vals.utmcsr,
'utm_medium': (vals.utmgclid) ? "cpc" : vals.utmcmd,
'utm_campaign': vals.utmccn,
'utm_content': vals.utmcct,
'utm_term': vals.utmctr
};
}());
// Find and split campaign name cookie
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
var campaignName = /[^(=)]*(?=\|utmcmd)/.exec(readCookie('__utmz'))
// Create cookie function
function setCookie(cname, cvalue, exdays, path) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires + ";domain=.align.ly;" + "path=" + path;
}
// If cookie is empty, create cookie. This should be one loop.
if (readCookie("source") === null) {
setCookie("source", GATrafficSource.utm_source, 1, '/');
}
if (readCookie("medium") === null) {
setCookie("medium", GATrafficSource.utm_medium, 1, '/');
}
if (readCookie("content") === null) {
setCookie("content", GATrafficSource.utm_content, 1, '/');
}
if (readCookie("keyword") === null) {
setCookie("keyword", GATrafficSource.utm_term, 1, '/');
}
if (readCookie("campaign") === null) {
setCookie("campaign", campaignName, 1, '/');
}
var gaCookie = document.getElementById('gaCookie');
if(gaCookie) {
gaCookie.value = {{GA - Cookie de usuario}}.substr(6,45);
}
// Add cookie info to hidden fields for web to lead fields
jQuery('input:hidden[name=ga_source]').val(readCookie('source'));
jQuery('input:hidden[name=ga_medium]').val(readCookie('medium'));
jQuery('input:hidden[name=ga_content]').val(readCookie('content'));
jQuery('input:hidden[name=ga_term]').val(readCookie('keyword'));
jQuery('input:hidden[name=ga_campaign]').val(readCookie('campaign'));
}, 2000); // The 2 second delay from the beginning
</script>Important: once we create this tag, we need to go to the one we created earlier and set it so that, after it fires, it fires this tag.

We create a Google Analytics user cookie
This step lets us extract the analytics Client ID.
We go to Variables and create a new user-defined variable. We select First-Party Cookie and enter the value «_ga«. Then we save it with the name «GA – User Cookie«:

We add fields to the Contact Form 7 form
It will probably work with other types of forms, but so far I’ve only tested it with Contact Form 7, although the original article was designed for Salesforce forms.
What you need to make sure of when creating the fields in the form is that they match what is specified in the code:

To store the cookie we only need a field with the value id=»gaCookie».
For the sources, they must be hidden inputs with the specified name, so inside the form we’ll insert the following fields:
[hidden gaCookie id:gaCookie]
[hidden ga_campaign]
[hidden ga_medium]
[hidden ga_source]
[hidden ga_content]
[hidden ga_keyword]Checks
We save the changes and publish the container.
Next, using a private browser window, we go to Google or to a website that contains a link to our site, so that we arrive via an intermediate page and can check that everything works correctly.
Once we reach the form page, we right-click on it and choose the inspect option to view the code and confirm that the fields are being filled in correctly:



