Skip to content

Instantly share code, notes, and snippets.

@krisb1220
Created August 8, 2023 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisb1220/d62c8802a7f47f449bc68c4b726b895b to your computer and use it in GitHub Desktop.
Save krisb1220/d62c8802a7f47f449bc68c4b726b895b to your computer and use it in GitHub Desktop.
This script will give all links on your wordpress website UTM codes. Almost definitely works on other sites, haven't tested it. The utm_id will give you the index that the link appears in a Nodelist of all <a> tags. Could be optimized to look for an href instead of <a> tags, but I made it quick and dirty for my own purposes.
function makeAllLinksHaveUtmCodes() {
let linksArray = Array.from(document.querySelectorAll("a")).filter(function(item){
return item.href&&item.href.split("?").length==1&&!item.href.includes("wordpress"); //returns items that have an href, no query, and aren't WP links
});
console.log(linksArray);
let pageTitle = document.title.split("-")[0].trim();
let linkID = 0;
linksArray.forEach(function(link){
link.href = (link.href.split("?")[0]+`?utm_source=${pageTitle}&utm_medium=website&utm_id=${link.id || linkID}`).toLowerCase();
linkID++
});
console.log(linksArray);
}
makeAllLinksHaveUtmCodes();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment