How to add utm_params to links

How to add utm query params to every external link on your blog

Every digital marketing knows the importance of utm query parameters, basically those text like utm_source=”” in your browser window location bar.
Its a great way to slice and dice and find out where traffic is coming from, which campaigns are more effective, is social working as expected.
Lets say you want to add these query params to your blog post so that the websites owners to whom you are linking can easily know how many clicks are coming through the website.
I had such a requirement for my blog http://jquer.in/ which now contains more than 5000 (function addUtmParams(source, medium, campaign) { $("a").each(function () { var $this = $(this); var linkHref = $this.attr("href"); if (linkHref.indexOf(window.location.hostname) < 0) { var updateLink = updateQueryString({ utm_source: source, utm_medium: medium, utm_campaign: campaign }, linkHref); $this.attr("href", updateLink); } }); })("jquer.in", "website", "content-curation"); // The thee configurable options ( utm_source, utm_medium, utm_campaign) // In my case source is jquer.in, medium is website, campaign is content-curation // Inspired from http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter function updateQueryString(params, url) { if (!url) url = window.location.href; for (var key in params) { if (params.hasOwnProperty(key)) { var value = params[key]; var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"); if (re.test(url)) { if (typeof value !== ‘undefined’ && value !== null) return url.replace(re, ‘$1′ + key + "=" + value + ‘$2$3′); else { var hash = url.split(‘#’); url = hash[0].replace(re, ‘$1$3′).replace(/(&|\?)$/, ”); if (typeof hash[1] !== ‘undefined’ && hash[1] !== null) url += ‘#’ + hash[1]; } } else if (typeof value !== ‘undefined’ && value !== null) { var separator = url.indexOf(‘?’) !== -1 ? ‘&’ : ‘?’, hash = url.split(‘#’); url = hash[0] + separator + key + ‘=’ + value; if (typeof hash[1] !== ‘undefined’ && hash[1] !== null) url += ‘#’ + hash[1]; } } } return url; }

View the functions file of jquer.in

Heres a gist

You can add the code to your functions.js or a javascript file of your wordpress theme.
Let me know what you think in the comments :-

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