Search code examples
google-analyticsgoogle-tag-manager

Google Analytics - Differentiate between home pages (subdomains)


The same tracking script exists across site.com and subdomain.site.com.

Everything works as desired, except both 'home pages' show as '/' and all the stats are combined.

I only have access to GTM and GA, with no access to make changes on the site. Any advice on how I can change the page name for only the subdomain home page in GA using GTM?


Solution

  • In the "fields to set" section of your Analytics tag (works for both Universal Analytics and GA4), you can overwrite the default value of the "page" field by adding a value to the page path when the user is on a subdomain. There are several more or less elegant ways to do that, but from the top of my head one would be to create a custom javascript variable (which is always and anonymous function that returns a value. Do not confuse it with the "javascript" variable type, which just returns the value of a variable from the global namespace).

    function() {
      if({{Page Hostname}} === "subdomain.mydomain.tld") {
         return [{{Page Hostname}},{{Page Path}}].join("/");
      }
      return {{Page Path}};
    }
    

    You have to enable the built-in page path and hostname variables for that to work. Then you drop this new variable into the page field. It will return the page path with the subdomain prepended if the user is on the subdomain, else just the regular page path.

    Or you use the same principle to just change the subdomain homepage

    function() {
      if({{Page Hostname}} === "subdomain.mydomain.tld" && {{Page Path}} == "/") {
         return [{{Page Path}},"subdomain-home"].join("/");
      }
      return {{Page Path}};
    }
    

    Instead of the array with a join you can just as well concatenate with the plus sign ({{Page Path}}+"/subdomain-home"), that's just personal preference.