Dynamic Universal Analytics Click Events in WordPress

The Marketing Department had a seemingly simple request: they wanted to implement click events for all links on the website that were pointing to a PDF file. But what’s the best way to do that?

Naturally we’re not going to add the required GA code by hand to every single href on the website. Doing a quick google search, some people accomplish this by adding a custom class to their links and targeting those links. That is fine if you want to categorize different types of links, but in our case we just want a simple, blanket rule that applies to all document links.

The JavaScript – Creating Click Events

So, first things first we need the JavaScript to add click events to every appropriate anchor on the page. Below is my solution, which I saved into my theme’s `/js` directory and called it `google-event-tracking.js`. I added some extra white space here to make it a bit easier to read.

jQuery(function($) {

  // Check if Google Analytics is Loaded
  if (typeof(ga) !== 'undefined') {

    // For every href linking to a pdf file...
    jQuery('a[href$=".pdf"]').each( function() {	

      jQuery(this).click( function(e) {

        var myHref = jQuery(this).attr('href');
        var fileName = myHref.substring(myHref.lastIndexOf("/")+1,myHref.length-4);

        //Pass the name of the file, sans file extension
        ga(['send', 'event', 'PDF', 'download', fileName]);  

      });

    });

  }

});

The WordPress Code

After uploading that file to my website, I just needed to update my `functions.php` and enqueue the new code. Note the use of the third parameter, which tells WordPress that our code requires jQuery to be loaded first.

function dynamic_google_pdf_tracking() {
    wp_enqueue_script(
        'google-event-tracking',
        get_stylesheet_directory_uri() . '/js/google_event_tracking.js',
        array( 'jquery' )
    );
}

add_action( 'wp_enqueue_scripts', 'dynamic_google_pdf_tracking' );

And that’s it! All links on the website that point to PDF files will automatically have click events applied to them.

Leave a Reply