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.
Source URL: http://wptheming.com/2013/10/add-utm-parameters-with-jquery/
0 comments:
Post a Comment