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^="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.

About Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

1 Response

  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

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=""> <strike> <strong>