Add UTM directly in any WordPress page not in admin (Traffic Source Tracking on 2nd page in WordPress)


When we want to know where the traffic is coming from, we share the link with UTM source. But if the User goes to another page from the shared page, the traffic becomes untraceable.

Example: Let’s say you have written an awesome blog post on your industry and you shared it on LinkedIn with UTM source. You will be able to track how many people read that article after you shared that on LinkedIn.

The readers enjoyed the article and a few of them clicked on the “contact us” page link, and filled out the form.

As the form is filled, you will not get to know that the traffic came from LinkedIn, Twitter or a regular reader.


In reality, you will be sharing your post on all the platforms.

Therefore, there should be a way to track the source of traffic and know the number of leads it generated.


For that specific use case, I rewrote this code snippet that automatically adds UTM source if the traffic is sent with a UTML source.


UTM data from 1st page is carried away to the 2nd-page visit and 3rd-page visit and so on. This makes traffic tracking easy.



It adds all the links present on the whole site resulting in tracking the traffic sources from previous pages.


<!– UTM Source JS starts> –>
function docReady(fn) {
// see if DOM is already available
if (document.readyState === “complete” || document.readyState === “interactive”) {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener(“DOMContentLoaded”, fn);

docReady(function () {
// Check if the user is logged in
<?php if ( ! is_user_logged_in() ) { ?>
// DOM is loaded and ready for manipulation here
console.log(“utm code reached!”);
// create urlParams variable (constant) from URLSearchParams class using current window
const urlParams = new URLSearchParams(;

// set UTM medium, source and campaign variables (constants) based on results of URSearchParams
const utm_medium = urlParams.get(‘utm_medium’) || “”
const utm_source = urlParams.get(‘utm_source’) || “”
const utm_campaign = urlParams.get(‘utm_campaign’) || “”
const utm_term = urlParams.get(‘utm_term’) || “”
const utm_content = urlParams.get(‘utm_content’) || “”

// get the Outbound button element
links = document.querySelectorAll(“a”);

links.forEach(function (outboundLink) {
// edit Outbound button element property by appending the URL parameters
outboundLink.href += “?utm_medium=” + utm_medium + “&utm_source=” + utm_source + “&utm_campaign=” + utm_campaign + “&utm_term=” + utm_term + “&utm_content=” + utm_content;

// log final Outbound button link to console
//alert( “utm added on!”+outboundLink.href);
<?php } ?>
<!– UTM Source JS ends! –>