Sitecore tip 43: Use Sitecore SXA and Google Tag Manager to track link clicks

I saw a question on the Sitecore Slack channel about the combination of SXA and tracking clicks on links with Google Analytics. The cool thing is that it is pretty easy to setup. The default Google Analytics component is not sufficient as it stores your GA tracking code to track page views etc. So you have to create a Google Tag Manager account and add it to your site and then do some smart stuff with rendering variants.

Here is how!

1. Add Google Tag Manager

This one is easy. Create a Google Tag Manager account and add the code to an HTML snippet item in SXA. Add this snippet in the meta partial design after the <body> tag.


2. Extend data template

For the components where you need this, let’s say the promo component, you have to extend the data template. Or in the correct way, create a new one and add an extra field. I called it something like “GATrackValue” (choose a user friendly display name afterwards). This field should hold the value that is stored in Google Analytics as the label. See the illustration below for an example.

3. Create a rendering variant

Create a new rendering variant which contains the link. The trick is to add a Data attribute that renders the field you have created in step 2. This can be done by using one of the hidden gems of SXA, field tokens! Yes you can use field values of a datasource item in your rendering variants by using the $(Fieldname) token. So in my example in step 2 this would be something like $(GATrackValue). See the image below for an example in which I added an Id attribute.

The output is rendered as follows:

<a id="Teaser Id 1" href="/Landingpage-1" data-variantitemid="{F687C5C2-FDD1-4B48-B0F8-C02C8EF8715A}" data-variantfieldname="Teaser link">Read more</a>

From here you have everything in place:

  • The id attribute contains a value that can be read from Google Tag Manager and stored in Google Analytics
  • The data-variantfieldname attribute can be used in Google Tag Manager as a click trigger to start the event and read the value

The data-variantfieldname attribute is always added to every link in your rendering variant and is always the same for a certain component. So this one can be used as a click trigger. This way you have a generic setup.

4. Configure Google Tag Manager click event

Last but not least you can configure a custom variable in Google Tag Manager for the data attribute. Use that variable in a trigger and use the trigger to create an event and store the value on the click event.

Because this article is about Sitecore I will not explain Google Tag Manager. There are plenty examples online available.

So this is a way to track link clicks in Google Analytics and define a value as a readable lable per link so your reports remain readable.