On a recent project we needed to add UTM query parameters (for Google Analytics tracking) to all outbound links to a specific domain.
I didn’t feel like updated all the links on the site directly in the code since these campaign query strings might change, so I created a basic jQuery plugin to do this:
jQuery.fn.utm_tracking = function() { $(this).find('a[href^="http://www.example.com"]').each(function() { var url = $(this).attr('href'); $(this).attr( 'href', url + '?utm_source=example&utm_medium=link&utm_campaign=campaign' ); }); }
The advantage of the plugin is that it can be called on just a section of the page (say the “#footer”), but you can also run it on the whole page:
$(document).ready( function() { $('body').utm_tracking(); });
Of course it could be more useful with the ability to add different parameters for different domains, etc:
jQuery.fn.utm_tracking = function(domain, source, medium, campaign) { $(this).find('a[href^="' + domain + '"]').each(function() { var url = $(this).attr('href'); $(this).attr( 'href', url + '?utm_source=' + source + '&utm_medium=' + medium + '&utm_campaign=' + campaign ); }); } // Example Call $(document).ready( function() { $('body').utm_tracking('http://www.example.com','example_source','example_link','example_campaign'); });
This script doesn’t take into account if the link already has a query string attached, so feel free to improve it or fork it on GitHub if you need that.
Hey there, Devin!
This helped a lot. Not only did it remind me how versatile jQuery was, but the idea of applying it to elements by extending jQuery seemed natural.
So I forked it in Git! I don’t know if I’m as graceful at coding as you or your other readers, but hoping that my UTM additions help others in the future. The addition lets you auto-replace the UTM variables of existing links, as well as can pull the UTM data for links from a parameter or the current URL.
There is also a very good WordPress plugin for capturing UTM and GCLID variables from URL. You can display them and you can pass them to your optin forms by using shortcodes. I highly recommend this plugin https://wordpress.org/plugins/handl-utm-grabber/