How do I install google tag manager correctly?

I read some tips & tricks, but they are a couple of years old and knowing that things are evolving quickly I am afraid that something has changed.
So can anyone suggest me the most correct and tested method?

Hi … if you mean Google Analytics Events Tags - then I can help you out …

if you’re just using Hugo for posts and stuff, then Google Tag Manager maybe overkill.

GA Event Tags are easy … and I even made a shortcode

2 Likes

what is the difference between Google Tag Manager and GA Event Tags?

Thats a good question for google … this is a good article on Tag Manager

Think of Tag manager as a way for you to manage ALL your ‘tags’ - for Google, Facebook, Google Ads, other ad networks, other analytics, etc

If you are happy with Google Analytics and just want Event Tracking … then stick with Google Analytics … and to implement GA event tagging, you just need to update your head.html to include a small script …

Assuming you have set your google_analytics_id in your config … then this will work

{{ "<!-- Global Site Tag (gtag.js) - Google Tag Manager -->" | safeHTML }}
{{ with .Site.Params.google_analytics_id}}
  <script async src="https://www.googletagmanager.com/gtag/js?id={{ . }}"></script>
  <script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', {{ . }});
  </script>
  {{ end }}

You then need to add the events … like onclick etc which I cover in my post on adding Event Tracking to Hugo

1 Like

Hi @nicovon … do you know what tracking code you are using? is it analytics.js or the google async tag code?

Hi, I simply added it to the baseof.html file of our theme.

mytheme/layouts/partials/footer-end.html

{{ $code := .Site.Data.config.googleAnalytics }}
      {{ if $code }}
      <script async src="https://www.googletagmanager.com/gtag/js?id={{ $code }}"></script>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
      
        gtag('config', '{{ $code }}');
      </script>
      {{ end }}

Nice … then I updated my instructions on event tracking when using gtag.js. As Google changed the way this works.

a gtag event tracking ‘button’ click looks like

<button onclick="gtag('event', <event>, {'event_category' : <category>, 'event_label' : <label>});">Example Button Text</button>