How can I track outbound links with Google Analytics?

I currently have a WordPress website, where I would like to be able to create an Event which tracks when visitors click through to a 3rd party web page (outbound link).

At present, my website has 3 Google Analytics Tracking Codes. Each Tracking Code looks as follows:

<script 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('config', 'UA-xxxxxxxx-x');
setTimeout("gtag('event', 'adjusted bounce rate', {'event_label':'more than 30 sec'})",30000 );
</script>

As you can see, I already have an Event integrated as to track visitors who spend at least 30 seconds on the page.

I have read through this Google Support page, where I can see that I would need to paste in:

<script>
var trackOutboundLink = function(url) {
   ga('send', 'event', 'outbound', 'click', url, {
     'transport': 'beacon',
     'hitCallback': function(){document.location = url;}
   });
}
</script>

and …

<a href="http://www.example.com" rel="nofollow noreferrer noopener" onclick="trackOutboundLink('http://www.example.com'); return false;">Check out example.com</a>

Now I know I would need to insert the above snippets into the header.php files but where I am uncertain, is:

  1. How could I integrate the above snippets so that they are ‘assigned’ to each of the 3 Google Analytics Tracking Accounts?
  2. Have I understood that the onclick attribute is only for use with the links we want to track on the page and not part of the Analytics Snippet, within the header.php file?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

First of all, you need to make sure you are using the same Analytics version tracking code. In your question, the main tracking code uses gtag.js but the event code is based on analytics.js.

You should use -as it’s newest- gtag.js. So, the code to use would be:

var trackOutboundLink = function(url) {
  gtag('event', 'clic', {
    'event_category': 'saliente',
    'event_label': url,
    'transport_type': 'beacon',
    'event_callback': function(){document.location = url;}
  });
}

It doesn’t matter where is placed this code as long as it goes after the main tracking code.

Nevertheless, in order to make it easier and avoid changing each external link, I recommend using Google Tag Manager. Here you have a tutorial to track external links through GTM.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply