Add UTM parameters with jQuery

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^=""]').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() {

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() {

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.

About Devin

I'm a WordPress developer based in Austin, Texas. I work with the fantastic crew at 10up and also run a little theme shop called DevPress. Find me on twitter @devinsays.

One thought on “Add UTM parameters with jQuery

  1. 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.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>