WordPress – How to track outbound links using Google Analytics

The following code can be added to your theme functions.php file (anywhere after the opening <?php line) to enable the tracking of outbound links (links to other website domains).

The code requires you to be using the universal analytics code, so if you haven’t already head over to here: Set up Universal Analytics: An overview.

The code inserts a jQuery script at the end of each page. The jQuery script will:

  • load once the page has finished loading
  • target all links in the article tag (you may have to change this to suit your website, or you could completely forgo it and just make it target all links using just ‘a’ instead of ‘article a’)
  • excludes anchor links, e.g. #top
  • when a user clicks on one of the links, a Google Analytics event is triggered recording the link as ‘Outbound traffic’, then the link is opened.

You can see if the jQuery script is working by opening your Google Analytics account for the website and going to Real-Time -> Events

You should see an event if a link as been clicked. When you click on Outbound Links you will see which link was clicked.

GoogleAnalytics-OutboundTrack1

After a few days the data will be available under Behavior -> Events -> Overview.

add_action('wp_enqueue_scripts', 'itsg_track_outbond_links',999);

function itsg_track_outbond_links() {
    add_action('wp_footer', 'itsg_track_outbond_links_js');
}

function itsg_track_outbond_links_js() {
?>
<script>
jQuery(document).ready(function() {

    jQuery("article a:not([href^='#'])").each(function() {
        var href = jQuery(this).attr("href");
        var target = jQuery(this).attr("target");
        var text = jQuery(this).text();
        var _gaq = _gaq || []; // in case _gaq is not defined - i.e. the analytics code has not ran on the page
        jQuery(this).click(function(event) { // when someone clicks these links
            event.preventDefault(); // don't open the link yet
             if (href.indexOf(window.location.host)==-1) {
                _gaq.push(["_trackEvent", "Outbound Links", "Clicked", href, , false]); // track outbound links
            }
            setTimeout(function() { // now wait 300 milliseconds...
                window.open(href,(!target?"_self":target)); // ...and open the link as usual
            },300);
        });
    });

});
</script> <?php
}