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.

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.

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