DataActs

How to track UTM parameters using Google Tag Manager

Usually, URLs are tough to understand as they have long links and random numbers in them. It becomes difficult for digital marketers to understand them and conclude the link/ campaign that brought traffic. 

UTM or Urchin Tracking Module parameters can easily sort your data to know from which campaigns the traffic is coming and which campaigns aren’t working out. UTM parameters are crucial for the sources where Google Analytics can’t identify the referrer. 

To say, an e-mail campaign. For Google Analytics, it will appear as a direct link as the user clicked on the link given in the e-mail. So it goes as Direct/ None in Google Analytics.

It is wise to handle your URL with UTM parameters to get clear data on where the traffic is coming from. You can easily build UTM URLs easily over the internet. 

Let’s have a look at the structure of a UTM link:

www.website.com/?utm_medium=email&utm_source=subscription&utm_campaign=random

In this link, look at the embolden words. This link contains three of the UTM parameters, let’s have a glance on them.

1. Utm_medium: This is the medium through which you get the traffic. If the traffic is coming from social media websites like Facebook, Instagram, Linkedin then you might want to name it as “social”.

2. Utm_source: This is the source of your traffic. It might be a newsletter that the user clicked on when you set up an email campaign.

3. Utm_campaign: Tells you about the campaign you are running. You may want to give its date as a name. Or you can also choose a name as Social Ads Campaign.

Besides this, there are two more parameters called:

4. Utm_content: Suppose there are more than one deals in your content and the user clicks on one of them. So obviously, you will want to know about the deal that interested him/ her. 

In an elaborated form, suppose you are selling a mobile phone over your site. The phone comes in 3 different types based on RAM, ROM, etc. Here, you have 3 deals based on which user will buy your product. Utm_content is where you put information about different models and you will get to know which phone was sold the most from which website. 

5. Utm_term: This is the term that you give to the URL. Like a paid search campaign no Facebook Analytics. 

Now, let’s talk about how to track their value in GTM and pass on to other pages.

Have a look at this code below and try to understand it.

(function(){
 
  if (!document.querySelectorAll) {
      return;
  }
 
  //(1)
  var currentUTMs = {},
      utmParams = [
        "utm_source",
        "utm_medium",
        "utm_campaign",
        "utm_content",
        "utm_term"
      ];
  //(2)
  var selector = 'change_this_string',
      targetURLs = document.querySelectorAll(selector);
  //(3)
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
 
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }
  //(4)
  function getUTMparam(arr, obj) {
    for (var i = 0; i < arr.length; i++) {
        var paramValue = getParameterByName(arr[i]);
        if (paramValue !== "") {
            obj[arr[i]] = paramValue;
        }
    }
  }
  //(5)
  function getItemLength(item){
    var count = 0, i;
    if (!!item && item.constructor === Object) {
        for (i in item) {
            if (item.hasOwnProperty(i)) {
                count++;
            }
        }
    } else if (!!item && item.constructor === Array) {
        for (i = 0; i < item.length; i++) {
            count++;
        }
    }
 
    return count;
  }
  //(6)
  function updateUrlParam(uri, key, value) {
    var i = uri.indexOf('#');
    var hash = i === -1 ? ''  : uri.substr(i);
        uri = i === -1 ? uri : uri.substr(0, i);
 
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        uri = uri.replace(re, '$1' + key + "=" + value + '$2');
    } else {
        uri = uri + separator + key + "=" + value;
    }
 
    return uri + hash;
  }
 
  getUTMparam(utmParams, currentUTMs);
 
  //(7)
  if (!!getItemLength(currentUTMs) && !!getItemLength(targetURLs) ) {
    for (var i = 0; i < targetURLs.length; i++) {
        if (targetURLs[i] !== null) {
            var href = targetURLs[i].getAttribute('href');
            if (href !== null) {
                for (var utm in currentUTMs) {
                    var newHref = updateUrlParam(href, utm, currentUTMs[utm]);
                    href = newHref;
                } 
                targetURLs[i].setAttribute('href', href);
            }
        }
    }
  }
})();

This above mentioned code is required to get the values of the UTM parameters so that later on attach them to the links you like. 

1. utmParams: This is a list of UTM parameters that you are going to work with. You can add and remove any parameter you want. The example UTM link above had only 3 parameters, you can also work with the number of parameters you want. 

2. Selector variable: This is where you put the UTM links[ as discussed above utm_content]. Change this value to the links you want or leave it empty if no specific link is required. Always change this value.

3. function getParameterByName(name): The name speaks for itself, it is a variable that gathers the values of the query strings [here, parameters] by their names.

4. function getUtMparam(arr, obj): This function will give you the values of all the parameters by their names into a single object, i.e. at a single array. 

5. function getItemLength(item): It will simply return the number of items that the object has.

6. function updateUrlParam(uri, key, value): You can see that it has 3 arguments in the ( ). These three arguments help update the key-value pairs of the given uri. 

7. The main code: This is where the magic happens. This function attaches the UTM parameters (if found any) in currentUTMs to targetURLS. 

If you do not fully understand the code, no problem because you just have to copy the code and paste it to implement it. Create a custom HTML tag and copy the code in it. Then all you have to do is fire this tag on the target pages where you want the UTM parameters to be attached to all the links. 

You can change the UTM parameters and set them as you wish just don’t alter the code if you don’t know much about it. These codes are very strict about there functionalities and even minor changes can produce errors/ undesired results. 

 

Conclusion:  In this article, we learned about the UTM parameters and the values they hold in traffic analysis. We’ve also learned how we can pass these UTM values onto other pages of the website. However, if you have any queries regarding it please feel free to mention in the comments section below. Stay tuned for the next article.

By Ranjan Kashyap

I am a seasoned Data Analyst and AI Engineer with deep expertise in leveraging sophisticated analytics and AI to drive strategic decisions. My technical acumen includes GA4, GTM, Mixpanel, and Amplitude implementations, along with robust data warehousing using BigQuery and Snowflake. I specialize in transforming complex datasets into actionable insights and optimizing business processes through advanced BI tools and CDP technologies. My approach helps businesses harness the full potential of their data, enhancing efficiency and promoting scalable growth.

Leave a comment