post-image

Google Analytics provides a number of extra tools for the adventurous to improve tracking and provide valuable insights. There are two types of tracking you can have - event tracking is used to help analyse visitor behaviour onsite. It’s not complicated to do this - but it’s time consuming and complex.

This Event Tracking or Google Tag Manager is additional code to the Hugo GA internal template.

Edit your Partial / Head file

Here is the example code for enable the tracking script

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

gtag('config', 'GA_TRACKING_ID');
</script>

You need to edit your Theme > Layouts > Partial > head.html and just before tag add this …

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{{ "<!-- Global Site Tag (gtag.js) - Google Tag Manager -->" | safeHTML }}
{{ with .Site.Params.google_analitycs_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 }}

See I made it work with Hugo and pull in your GA ID from your config.toml

Allow RAW Html in Markdown

By default and for good safety reasons, Hugo doesnt process HTML in Markdown files. You need to add this to your config.toml, if you own the site and understand the risk …

1
2
[markup.goldmark.renderer]
unsafe = true

Tracking Button Clicks

So now you want to track someone clicking on a link in your website … Here is the basic code

<button onclick="ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);">Example Button Text</button>

Then in your markdown file you make it like this ..

1
<a onclick="ga('send', 'event', 'GA', 'Example', 'Link');" href="http://google.com" target="_blank">See the little example</a>

Testing

So now go to Google Analytics and check your events have showed up :)

Only have this code on Production

So you tested this … let’s do one last thing and only have this script added if we are building the live site … and this extra code, and the code on longer be in your head.html if you run a localhost server

1
2
3
4
5
{{ if in (.Site.BaseURL | string) "www.example.com" }}
<script>
    // ... Google Tag Manager tracking code
</script>
{{ end }}

How are you using Event Tracking? If you need assistance to implement Event Tracking get in contact.

Linkage