Aleš Sýkora / November 28, 2023 / 0 comments
Tracking events with Google Tag manager & WordPress
min read / WordPress / Share on: Twitter, LinkedIn, Facebook
Post summary: Add numbers to your content with Google Tag Manager & Google Analytics Events.
This tutorial is made especially for those who switched to the Gutenberg editor and found very complicated to add onclick events to the links and other elements. I was thinking about some better Google Analytics data and found this code (download) for standard Google Analytics which tracks some cool events:
Advanced Tracking 1.0
- Copy to clipboard
- Scroll Depth
- Text lenght
- Image Count
- Social tracking
- Time Spent
<script>
var _0x5d8e=["readyState","complete","name","get","getAll","gtm","indexOf",".send","event","send","social","body","getElementsByTagName","undefined","copy","Advanced tracking","Copy to clipboard","substring","trim","textContent","target","addEventListener","onscroll","document","documentElement","scrollHeight","offsetHeight","clientHeight","max","innerHeight","scrollTop","pageYOffset","Scroll","20%","40%","60%","80%","100%","pathname","location","[\?&#]","=([^&#]*)","exec","edge.create","Facebook","Like","subscribe","Event","edge.remove","Unlike","message.send","Share","nodeName","IFRAME","src","url","Twitter","tweet","bind","events","ready","Time spent","15s","setTimeout","30s","45s","60s","75s","90s","105s","120s","length","","replace","round","img","Text length","Image count"];(function(){try{if(document[_0x5d8e[0]]===_0x5d8e[1]){mainAdvancedTracking()}else {var interval=setInterval(function(){if(document[_0x5d8e[0]]===_0x5d8e[1]){clearInterval(interval);mainAdvancedTracking()}},250)};function mainAdvancedTracking(){
var copyToClipboard = true;
var scrollTracking = true;
var textLength = true;
var imageCount = true;
var socialTracking = true;
var timeSpent = true;
var trackerName=ga[_0x5d8e[4]]()[0][_0x5d8e[3]](_0x5d8e[2]);var isGTMhere=false;if(trackerName[_0x5d8e[6]](_0x5d8e[5])> -1){isGTMhere=true};function sentEventToGA(eCat,eAct,eLab){if(isGTMhere){ga(trackerName+_0x5d8e[7],_0x5d8e[8],{eventCategory:eCat,eventAction:eAct,eventLabel:eLab,nonInteraction:1})}else {ga(_0x5d8e[9],_0x5d8e[8],eCat,eAct,eLab,{"nonInteraction":1})}}function sentSocialToGA(eCat,eAct,eLab){if(isGTMhere){ga(trackerName+_0x5d8e[7],_0x5d8e[10],{eventCategory:eCat,eventAction:eAct,eventLabel:eLab})}else {ga(_0x5d8e[9],{hitType:_0x5d8e[10],socialNetwork:eCat,socialAction:eAct,socialTarget:eLab})}}try{if(copyToClipboard){var hbody=document[_0x5d8e[12]](_0x5d8e[11])[0];if( typeof (hbody)!==_0x5d8e[13]){hbody[_0x5d8e[21]](_0x5d8e[14],function(evt){sentEventToGA(_0x5d8e[15],_0x5d8e[16],evt[_0x5d8e[20]][_0x5d8e[19]][_0x5d8e[18]]()[_0x5d8e[17]](0,100))})}}}catch(err){};try{if(scrollTracking){var flag20=true;var flag40=true;var flag60=true;var flag80=true;var flag100=true;window[_0x5d8e[22]]=function(e){var body=window[_0x5d8e[23]][_0x5d8e[11]],html=window[_0x5d8e[23]][_0x5d8e[24]];var delkaStranky=Math[_0x5d8e[28]](body[_0x5d8e[25]],body[_0x5d8e[26]],html[_0x5d8e[27]],html[_0x5d8e[25]],html[_0x5d8e[26]]);var velikostOkna=window[_0x5d8e[29]]||document[_0x5d8e[24]][_0x5d8e[27]]||document[_0x5d8e[11]][_0x5d8e[27]];var pozice=(window[_0x5d8e[23]][_0x5d8e[30]]||window[_0x5d8e[31]])+velikostOkna;if(pozice>0){var procenta=(pozice/delkaStranky)*100};if((flag20)&&(procenta>20)){sentEventToGA(_0x5d8e[15],_0x5d8e[32],_0x5d8e[33]);flag20=false};if((flag40)&&(procenta>40)){sentEventToGA(_0x5d8e[15],_0x5d8e[32],_0x5d8e[34]);flag40=false};if((flag60)&&(procenta>60)){sentEventToGA(_0x5d8e[15],_0x5d8e[32],_0x5d8e[35]);flag60=false};if((flag80)&&(procenta>80)){sentEventToGA(_0x5d8e[15],_0x5d8e[32],_0x5d8e[36]);flag80=false};if((flag100)&&(procenta>99)){sentEventToGA(_0x5d8e[15],_0x5d8e[32],_0x5d8e[37]);flag100=false}}}}catch(err){};try{if(socialTracking){var mpath=document[_0x5d8e[39]][_0x5d8e[38]];function extractParamFromUri(uri,paramName){if(!uri){return};var regex= new RegExp(_0x5d8e[40]+paramName+_0x5d8e[41]);var params=regex[_0x5d8e[42]](uri);if(params!=null){return unescape(params[1])};return}FB[_0x5d8e[47]][_0x5d8e[46]](_0x5d8e[43],function(targetUrl){sentSocialToGA(_0x5d8e[44],_0x5d8e[45],mpath)});FB[_0x5d8e[47]][_0x5d8e[46]](_0x5d8e[48],function(targetUrl){sentSocialToGA(_0x5d8e[44],_0x5d8e[49],mpath)});FB[_0x5d8e[47]][_0x5d8e[46]](_0x5d8e[50],function(targetUrl){sentSocialToGA(_0x5d8e[44],_0x5d8e[51],mpath)});function trackTwitter(intent_event){if(intent_event){var opt_pagePath;if(intent_event[_0x5d8e[20]]&&intent_event[_0x5d8e[20]][_0x5d8e[52]]==_0x5d8e[53]){opt_target=extractParamFromUri(intent_event[_0x5d8e[20]][_0x5d8e[54]],_0x5d8e[55])};sentEventToGA(_0x5d8e[56],_0x5d8e[51],mpath)}}twttr[_0x5d8e[60]](function(twttr){twttr[_0x5d8e[59]][_0x5d8e[58]](_0x5d8e[57],trackTwitter)})}}catch(err){};try{if(timeSpent){window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[62])},15000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[64])},30000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[65])},45000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[66])},60000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[67])},75000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[68])},90000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[69])},105000);window[_0x5d8e[63]](function(){sentEventToGA(_0x5d8e[15],_0x5d8e[61],_0x5d8e[70])},120000)}}catch(err){};try{var tLen=document[_0x5d8e[12]](_0x5d8e[11])[0][_0x5d8e[19]][_0x5d8e[18]]()[_0x5d8e[73]](/ /g,_0x5d8e[72])[_0x5d8e[73]](/(?:rn|r|n)/g,_0x5d8e[72])[_0x5d8e[71]];tLen=Math[_0x5d8e[74]](tLen/100)*100;var imgLen=document[_0x5d8e[12]](_0x5d8e[75])[_0x5d8e[71]];if(textLength){sentEventToGA(_0x5d8e[15],_0x5d8e[76],tLen)};if(imageCount){sentEventToGA(_0x5d8e[15],_0x5d8e[77],imgLen)}}catch(err){}}}catch(err){}})()
</script>
Yes, it is possible to use this script (in header.php or as a custom HTML tag in Tag Manager), but I want to use standard funcionality of Google Tag Manager. Simply because I never trust to these “big” scripts.
So I started to think about how to do that. I have read a lot of content about Tag Manager from Simo Ahava blog and lot from others. Then I decided to go with simple, but for me the best solution. I do not have big Analytics skills and I do not need really big and complicated metrics.
So I have prepared this tracking events in Tag Manager:
Advanced Tracking 2.0
- Tracking of File Downloads
- Tracking clicks on E-mail link
- Tracking clicks on Phone link
- Tracking clicks on Picture detail (designed fro Gutenberg Image Block)
- Tracking clicks on Gallery detail (designed fro Gutenberg Gallery Block)
- Tracking clicks on External link
- Tracking clicks on Internal link
- Tracking Scroll Depth
- Tracking Time Spent on website
- Tracking Copied text
I know that it can propably be made better. Following setup is very good for better understanding what people look for and what they do on my websites. I will be happy if it be useful for you too. If you have any suggestions share it it the comments below please :-).
Tracking File Download with Tag Manager
You need to decide which file extensions you want to track as a file download.
I am fine with these: .pdf .xlsx .docx .csv .zip .rar .7zip .xls .doc
Let’s start with preparing Event in Google Tag Manager. For Tracking Downloads you will need to setup one Tag and one Trigger and one custom Variable.
Tracking Title of downloaded file with custom variable
I want to see which file has been downloaded. When I create the content I add the Title attribute to the links so I need to take those titles to the game.
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Auto-Event Variable
- Variable Type = Element Attribute
- Attribute Name = title
- Save, Name of your Variable = Attribute Title
File Is Downloaded Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – Just Links
- Trigger fires on = Some Link Clicks
- Fire this trigger when an Event occurs and all of these conditions are true: Click URL Matches RegEx .(pdf|xlsx|docx|csv|zip|rar|7zip|xls|doc)$
- Save, Name of your Trigger = Link – File
File Downloads Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Download file
- Label = {{Attribute Title}}
- (optional) Value = {{Page Path}}
- Triggering – Select the pre-created trigger Link – File
- Save, Name your Tag = EVENT – Download Link
Tracking click on E-mail link With Tag Manager
This Event tracks every click on link which use the mailto: value. For example:
<a href="mailto:[email protected]" title="Send e-mail to Aleš Sýkora">[email protected]</a>
Let’s create the Trigger and Tag. As a variable, I will use the Attribute Title again.
user click on mail link Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – Just Links
- Trigger fires on = Some Link Clicks
- Fire this trigger when an Event occurs and all of these conditions are true: Click URL Contains mailto:
- Save, Name of your Trigger = Link – Mail
E-Mail link click Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = E-mail link click
- Label = {{Attribute Title}}
- (optional) Value = {{Page Path}}
- Triggering – Select the pre-created trigger Link – Mail
- Save, Name your Tag = EVENT – E-Mail Link
Tracking Click On Phone Link With Tag Manager
This Event tracks every click on link which use the tel: value. For example:
<a href="tel:00420 604 973 176" title="Aleš Sýkora Phone Contact">00420 604 973 176</a>
Let’s create the Trigger and Tag. As a variable, I will use the Attribute Title again.
user click on Phone link Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – Just Links
- Trigger fires on = Some Link Clicks
- Fire this trigger when an Event occurs and all of these conditions are true: Click URL Contains tel:
- Save, Name of your Trigger = Link – Phone
Phone link click Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Phone link click
- Label = {{Attribute Title}}
- (optional) Value = {{Page Path}}
- Triggering – Select the pre-created trigger Link – Phone
- Save, Name your Tag = EVENT – Phone Link
Tracking Click On Image in Gutenberg Image Block With Tag Manager
Next thing I want to track are screenshots. What if big amount of people open image detail? They really want to know more about! I recently switched my content to the Gutenberg and make images clickable so they appear in lightbox (Image > Link to > Media File + Simple Lightbox plugin). How to track them? Let’s see. And again l will use the Attribute Title variable. We will also create new variable for Attribute Alt.
Tracking Alt Attribute of clicked image
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Auto-Event Variable
- Variable Type = Element Attribute
- Attribute Name = alt
- Save, Name of your Variable = Attribute Alt
open Image in lightbox Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – All Elements
- Trigger fires on = Some Clicks
- Fire this trigger when an Event occurs and all of these conditions are true: Click element matches CSS selector figure.wp-block-image a img
- Save, Name of your Trigger = Click – Image
Gutenberg Image click tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Picture Detail
- Label = Title = {{Attribute Title}}
- Value = Alt = {{Attribute Alt}}
- Triggering – Select the pre-created trigger Click – Image
- Save, Name your Tag = EVENT – Picture Detail
Tracking Click On Image In Gutenberg Gallery Block With Tag Manager
Image and gallery means different things for me. So I prepared the tutorial to respect this. Because Picture is one big picture, but gallery are especially two or more pictures. I want to track click on gallery independently.
open Gallery Image Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – All Elements
- Trigger fires on = Some Clicks
- Fire this trigger when an Event occurs and all of these conditions are true: Click element matches CSS selector li.blocks-gallery-item figure a img
- Save, Name of your Trigger = Click – Gallery Image
Gutenberg Gallery Image click Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Gallery Detail
- Label = Title = {{Attribute Title}}
- Value = Alt = {{Attribute Alt}}
- Triggering – Select the pre-created trigger Click – Image
- Save, Name your Tag = EVENT – Gallery Detail
Tracking click on External Link With Tag Manager
It would be nice to know which external links are popular among website visiters.
External Link Click Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – Just Links
- Trigger fires on = Some Links Clicks
- Fire this trigger when an Event occurs and all of these conditions are true:
- Click URL does not match RegEx .*toolset.wiki.+ (change toolset with your domain name, wiki with domain extension .com etc.)
- Click URL does not contain mailto: (we already use other tag for tracking mailto: links)
- Click URL does not contain tel: (we already use other tag for tracking tel: links)
- Save, Name of your Trigger = Link – External
External Link Click Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = External Link
- Label = {{Attribute Title}}
- Value = {{Click URL}} (built in variable)
- Non-interaction hit = True (This event will not change your bounce rate, because it will not be counted as an interaction on your site. This makes sense for outbound links, but for many other events you may want to count the event as an interaction.)
- Triggering – Select the pre-created trigger Link – External
- Save, Name your Tag = EVENT – External Link
Tracking Click On Internal Link With Tag Manager
Internal Link Click Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Click – Just Links
- Trigger fires on = Some Links Clicks
- Fire this trigger when an Event occurs and all of these conditions are true:
- Click URL matches RegEx .*toolset.wiki.+ (change toolset with your domain name, wiki with domain extension .com etc.)
- Click URL does not match CSS selector figure.wp-block-image a (we already use other tag for tracking clicks on images)
- Click URL does not match CSS selector li.blocks-gallery-item-figure a (we already use other tag for tracking on gallery images)
- Click URL does not contain mailto: (we already use other tag for tracking mailto: links)
- Click URL does not contain tel: (we already use other tag for tracking tel: links)
- UPDATE! add also this: Click URL does not match RegEx .(pdf|xlsx|docx|csv|zip|rar|7zip|xls|doc)$
- Save, Name of your Trigger = Link – Internal
Internal Link Click Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Internal Link
- Label = {{Attribute Title}}
- Value = {{Click URL}} (built in variable)
- Triggering – Select the pre-created trigger Link – Internal
- Save, Name your Tag = EVENT – Internal Link
Tracking Scroll on page With Tag Manager
Do you know how much your visitors read the content? You want to show banner in footer but is it a good idea? Check the scroll level with Tag Manager.
Activate Scroll Variables Built in Tag Manager
- Open Google Tag Manager > Variables > Under Built-In Variables Click on Configure
- Under Scrolling section Check:
- Scroll Depth Threshold
- Scroll Depth Units
- Scroll Direction
Scroll Depth Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Scroll Depth
- Check Vertical Scroll Depths
- Percentages = 20, 40, 60, 80, 100 (you can use your own)
- Enable this trigger on: Window Load (gtm.load)
- This trigger fires on All Pages
- Save, Name of your Trigger = Scroll – 20, 40, 60, 80, 100
Scroll Depth Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Scroll Depth
- Label = {{Scroll Depth Threshold}}
- Triggering – Select the pre-created trigger Scroll – 20, 40, 60, 80, 100
- Save, Name your Tag = EVENT – Scroll
Tracking Time Spent on website
This event tracks the whole time user spent on your website. It is up to you if you want track the whole time or only several times the interval 15s (or your own interval).
Time spent Custom Variables In Tag Manager
timer Event Label
This variable is made for formatting the Event label in Analytics.
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Custom JavaScript and add JavaScript code from below
- Save, Name of your Variable = timerEventLabel
function() {
var elapsed = {{timerEventNumber}} * {{timerInterval}} / 1000;
var min = Math.floor(elapsed/60);
var sec = elapsed % 60;
return min + 'm ' + sec + 's';
}
Timer Event Number
This variable is made for calculating the final time.
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Data Layer Variable
- Data Layer Variable Name = gtm.timerEventNumber
- Data Layer Version = Version 2
- Save, Name of your Variable = timerEventNumber
Timer Interval
This variable save the interval for calculations of final time.
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Data Layer Variable
- Data Layer Variable Name = gtm.timerInterval
- Data Layer Version = Version 2
- Save, Name of your Variable = timerInterval
Timer Trigger
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Timer
- Event name = gtm.timer
- Interval = 15000 (15s)
- Limit = blank (you can limit the timer events here. For example 1 = display only 15s; 5 = display maximum 1 minute 15s)
- Enable this trigger when all of these conditions are true Page URL matches RegEx .*
- This trigger fires on All Timers
- Save, Name of your Trigger = Timer – 15s
Time on Website Tracking Event
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Time Spent
- Label = {{timerEventLabel}}
- Triggering – Select the pre-created trigger Timer – 15s
- Save, Name your Tag = EVENT – Time Spent
Tracking Clipboard text (ctrl+C) event in Tag Manager
This event is very cool for me. I can easy decide what visitors are looking for and I can also check if someone try to steal my texts.
Copy text custom Variable In Tag Manager
- Open Google Tag Manager > Variables > Under User-Defined Variables Click on New
- Choose variable type Data Layer Variable
- Data Layer Variable Name = clipboardText
- Data Layer Version = Version 2
- Save, Name of your Variable = Copytext-variable
Clipboard text Trigger Tag Manager
- Open Google Tag Manager > Triggers > Click on New
- Trigger Type = Custom Event
- Event name = textCopied
- This trigger fires on All Custom Events
- Save, Name of your Trigger = Copytext
Custom Copytext Listener
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Custom HTML and fill in the code from below
- Triggering – All Pages (you can use your own trigger if you want)
- Save, Name your Tag = Custom Copytext Listener
<script>
// Declare function to get selected text from document
function getSelectionText() {
var text = '';
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != 'Control') {
text = document.selection.createRange().text;
}
return text;
}
// Declare function on copy event
document.addEventListener('copy', function(e){
dataLayer.push({
'event': 'textCopied',
'clipboardText': getSelectionText(),
'clipboardLength': getSelectionText().length
});
});
</script>
Text copied Event for Google Analytics in Tag Manager
- Open Google Tag Manager > Tags > Click on New
- Set Tag Type to Universal Analytics
- Set Track Type to Event
- Fill the Event Tracking Parameters
- Category = Advanced Tracking 2.0
- Action = Text Copied
- Label = {{Copytext-variable}}
- Triggering – Select the pre-created Custom Event – Copytext
- Save, Name your Tag = EVENT – Text Copied
That’s all for now. Do not forget to publish your GTM container and wait for events in Google Analytics. I will continue with adding some event tracking snippets if I would need one :). Hope it helps! It should look like this.
Fuel my passion for writing with a beer🍺
Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻