Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track utm_source in Google Analytics using gtag?

I'm having difficulties tracking utm_source, utm_medium with gtag. I have an SPA in AngularJS, so all the page views are fired dynamically. I've been looking for solutions to track these values from gtag, but the only hint I found is this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments)};
  gtag('js', new Date());

  gtag('set', 'page_title', 'FBIA: '+ia_document.title);
  gtag('set', 'campaignSource', 'Facebook');
  gtag('set', 'campaignMedium', 'Social Instant Article');

  gtag('config', 'UA-XXXXXXXX-X');
</script>

Source: https://gist.github.com/danielmcclure/559c2fe2433035f72d80fe45755af7bf

Unfortunately this is not working for me, neither for others:

https://www.en.advertisercommunity.com/t5/Google-Analytics-Code/How-can-you-set-Campaign-Source-Medium-etc-with-custom-values/td-p/1307828

Any better ideas?

like image 799
Faluvegi Ferenc Avatar asked May 08 '18 10:05

Faluvegi Ferenc


2 Answers

Finally I managed to find this out, by beautifying the gtag.js code and searching for "campaignSource". It seems the current method is:

gtag('config', 'YOUR_TRACKING_ID', {
  ...some_other_configs,
  campaign: {
    source: 'Some source', // utm_source
    medium: 'Some medium' // utm medium
  }
});

It's a shame that there isn't a comprehensive documentation of gtag. But at least I wasn't forced to switch back to ga...

like image 61
Faluvegi Ferenc Avatar answered Sep 19 '22 04:09

Faluvegi Ferenc


I also needed utm_campaign and utm_content as well. Anything you don't set seems to get wiped out, so I also searched code and found I could do this: (note the ga prefixed variables are things I determined in earlier JavaScript

gtag('config', 'YOUR_TRACKING_ID', {
    campaign: {
        medium: gaMedium,
        source: gaSource,
        name: gaCampaign,
        content: gaContent
    }
});
like image 29
JustTrying Avatar answered Sep 21 '22 04:09

JustTrying