WordPress Link Tracking – FREE, NO PLUGIN Method

WordPress is the straight dope of content management systems (CMSs) for everyone from non-tech savvy bloggers, to tech-competent SEOs, and even the hyper tech nerds that look down on PHP.  However, like any CMS, it’s got a few quirks here and there that can be annoying.  If you have ever tried to add a simple “onClick” event to a link in your WordPress posts/pages, you’ll notice that WordPress strips out Javascript from content added in its editor.  This is a security feature and is common among many CMS systems, not just WordPress, but its annoying nonetheless.

If you wanted to track your internal or outbound links for whatever reason (i.e.: affiliate links, etc.) one of the easiest ways to do this is through a simple onClick event in your HTML links.  However this isn’t possible with WordPress stripping out JS, so how do be get around this?

There are a few ways to add onClick tracking to your WordPress content, including:

  1. Disabling the WYSIWYG Editor in WordPress – WordPress will allow Javascript in the post editor, but only if you disable the “What You See is What You Get” version, and only use the pure text editor.  This makes formatting pages like using Notepad. Not fun.
  2. Disabling the Javascript stripping security feature within WordPress’ settings – I’m actually unclear how exactly to do this, but I’m very clear on the fact that it’s strongly discouraged as a big security vulnerability.  Not an option.
  3. Using a Plugin – Most WordPress Tutorial sites tell you to install plugins.  Is that really a tutorial? Anyway, my stance on plugins is clear: Use only when absolutely necessary.  Never place the functionality, viability, speed, and security of your site in some random developers hands.
  4. Creating a Shortcode which includes your link and appropriate tracking code. – Easy to do and completely follows the security guidelines (i.e. Javascript can be generated at the PHP/Shortcode level, and not vulnerable to injection at the CMS editor level).  The downside here is that you’ll need to manually enter each link that you want to track.  This is what I used to do, and I’ve included a guide below.
  5. Use Javascript to modify your links with appropriate tracking codeDing Ding Ding! I love this method, because it gives you central control over your tracking, affects every link on every page of your site (without needed Search and Replace).  You can add onClick code, change nofollow attributes, sponsored attributes, and have different rules for different types of links!

Ok, so how do we do it?  Let’s dive in!

Link Tracking in WordPress with Javascript

Tracking your links in WordPress using Javascript code is relatively easy, but does require a tiny bit of knowledge of Javascript and PHP.  Don’t worry, I’ll walk you through it all.  Let’s jump right in:

  1. Edit your theme’s “functions.php” file.  This can be access via “Appearance” -> “Theme Editor” on your WordPress admin menu.  Copy in the following:
function affiliate_link_tagging(){
?>
<script>
var trackOutboundLink = function(label) {
gtag('event', 'click', {
'event_category': 'outbound',
'event_label': label,
'transport_type': 'beacon',
//'event_callback': function(){document.location = url;}
});
}
var flags_to_check = ["amzn.to","tag="];
var flags_match_string = flags_to_check.join("|");

for(var i = 0; i < document.getElementsByTagName("a").length; i++){
if(document.getElementsByTagName("a")[i].href.match(flags_match_string)){
document.getElementsByTagName("a")[i].setAttribute("rel","nofollow sponsored")
document.getElementsByTagName("a")[i].addEventListener("mousedown",(e)=>{trackOutboundLink("Affiliate Link Click")})
}
}
</script>
<?php
}

add_action('wp_footer','affiliate_link_tagging');
  1. Edit the “trackOutboundLink” function to be whatever function you want to track.  This could be any Javascript code.  I’ve used an off-the-shelf Google Analytics event tracking function.  Note: This takes as an argument the “label” of the event captured in GA.  Since I’m tracking affiliate links, I’ve labeled it as such, but you can change that as appropriate.
  2. Edit the “flags_to_check” array to include any pattern you want to match.  I’ve included amzn.to for Amazon affiliate shortened links, and “tag=” for Amazon affiliate non-shortened links.  You’re links may differ.  NOTE: For tracking all external links, you’ll need to have a different logic on your pattern, can you guess what it might be?
  3. Done!

How WordPress Link Tracking with Javascript Works

Let’s take a short moment to talk about how exactly this code works, it goes like this:

  1. functions.php loads every time you load a page on your WordPress site.
  2. PHP’s ultimate job is to generate HTML code.  HTML code can contain Javascript (as long as its in the <script></script> tag).
  3. In functions.php, we declare a function (affiliate_link_tagging()), that’s only job is to generate HTML, i.e. the <script>…</script> code we see above.  More info is below on the actual JS code that’s in the <script> tag.
  4. We use a WordPress “hook” to tell WordPress to run the affiliate_link_tagging function at the footer of the page.  This part is actually very important, we can’t run this code in the header or through the normal “wp_enqueue_scripts” hook, since it needs all the content on the page to load first.
  5. Now that we have loaded this JS code into our footer, it will be run by our browser every time a page loads.  The JS code is where the magic happens and the links are modified.
  6. The JS code does the following: cycles through every link on the page (the “for” loop), checks whether the link URL (“href”) matches the pattern (“href.match()”), if it does, it goes to work.
  7. If it finds a match, it first changes the “rel” attribute to be “nofollow sponsored”.  You can adjust this if you don’t want to nofollow/etc your links, but it’s standard practice in affiliate marketing.
  8. It sets an event listener to execute your tracking code everytime someone “mouses down” on the link.  This could also be “mouseup”.  NOTE: Unintuitively, the .onclick method doesn’t work here, but we are aiming to emulate the HTML “onClick” attribute.
  9. All this happens incredibly fast and immediately as the page loads, so while it’s not on the source code, the links are changed immediately.

A couple of notes and caveats for SEOs:

  1. “Viewing source” will NOT show the changes, however “Inspect”-ing them with your browser will.  This is because “View source” is only the exact text that was delivered to your browser, while “inspect” shows the results of your browser rendering the code, i.e. executing the JavaScript.
  2. If you are using Screaming Frog or other crawlers to diagnose SEO issues, you must set it to “render” your pages.
    1. Side note here: Ahrefs does a good job at rendering JS, however as of this writing SEMRush still doesn’t render JS during their audits.
  3. And don’t worry, Google absolutely DOES render JS, so your nofollow/sponsored attributes will be seen by big G.

Advantages of WordPress Link Tracking With Javascript

As with anything in coding, there are multiple ways to achieve any objective, but in my opinion this methods fits the use case of most WordPress users and site owners.  Why is it so advantageous to use this type of Javascript tagging instead of relying on PHP to generate the appropriate tags? See below:

  1. Centralized management – These code affects EVERY LINK on EVERY PAGE of your site, instantly.    If you link to another affiliate site? Add the flag for that site.  Don’t want to label your links as sponsored anymore? One line of code needs to change.  Add an analytics system and have new tracking code?  Super easy.
    PHP shortcodes are managed centrally, but they need to me added to each page, necessitating Search/Replace and adding additional work when publishing new content.  Using JS allows us to seamlessly layer on some code and not have any additional processes for writers and editors.
  2. Change more than just tracking code – As shown above, you aren’t just appending text to your <a> tags, with JS you can dynamically change every aspect of your links.  In the above we changed event listeners to track clicks, and rel attributes to appropriately tag them as nofollow and sponsored.  However, we aren’t limited to that.  You could also add your own custom HTML attributes, tack on dynamic tracking parameters to the end of the target URL (like referring page or even userID for instance), or anything else that’s accessible within the DOM.
  3. No Plugins! –  With this simple copy/paste code, you avoid downloading a plugin that may be insecure, may cost you money, and may become outdated and break your site in the future, and contains unknown numbers of lines of code to bog down and introduce vulnerabilities to your site.  With this code you take the power in your own hands and truly own your site.

 

Link Tracking in Javascript with Shortcodes

This might be a little intimidating if you’ve never done it before, but it’s quite easy.  It’s comes down to:

  1. Define a function in your functions.php file.
  2. Declare that function as a shortcode.

Done!

So for our purposes we are going to:

  1. Define the “link_function()” function.  This takes a URL and a bit of text and spits out a full HTML link with whatever additional code we want, in this case a Google Analytics tracking code.
  2. Declare the “link_function()” function to power the [[link]] shortcode.
  3. Wherever we want a tracked link within our posts, we just use the [[link url=”https://www.example.com”]]Link Text[[/link]] code instead of a regular link.

Add Code to Your functions.php

Let’s look at the code!  See below:

 

/* BEGIN CODE */
//Reminder: Place this in your functions.php file.  I put it all the way at the bottom of the file.
function link_function($atts, $content = null){
$code_return = '';

$a = shortcode_atts( array(
'url' => '',
), $atts );

$url = $a['url'];
$tracking = " onclick=\"ga('send', 'event', 'Link', 'Click', 'Purchase Details');\" "; 
//This is using the ga.js standard, make sure it conforms with your tracking code event tracking.
//Also, obviously, swap out the event categories with appropriate values. 
//More info here: https://developers.google.com/analytics/devguides/collection/analyticsjs/events
$code_return .= '' . $content .'';

return $code_return;
}
add_shortcode( 'link', 'link_function' );
/* END CODE */

Putting the Links in Posts

After this code is implemented, it’s as simple as using the shortcode for any links you want to track.  I.e.:

This is wonderfully optimized bit of text meant to lead you to click on [[link url=”https://www.example.com/product-page?affiliate-code=michael-hayes”]]this link[[/link]].

Simple right?

Conclusion

Tracking link clicks in WordPress is crucial if you are going to understand how your content is performing.  As with anything in coding, there are multiple ways of doing this, but the best way, in my opinion, is using Javascript to modify your links appropriately after the page loads.  Doing this allows us to not only add a tracking function, but also adjust important elements of links such as “rel” attributes, custom HTML attributes, appending parameters to URLs, and sending appropriate data to our analytics based on custom logic.

Leave a Comment

Your email address will not be published. Required fields are marked *