WordPress not allowing rewriting HREF with url parameters using Javascript?

First, I’m not a developer by training.
I’m converting our site to WordPress and having trouble rewriting HREFs to include url parameters I’ve stored in localStorage.

On the current site, this script works reliably.

function getAllUrlParams() {
//assign URL parameters to variable
console.log(“URL Params loaded”);
var queryString = window.location.search.substring(1);

if (queryString) {
//split queryString into pairs
var pairs= queryString.split(‘&’);
console.log(pairs);

//split pairs into object
var result = {};
pairs.forEach(function(pair) {
pair = pair.split(‘=’);
result[pair[0]] = decodeURIComponent(pair[1] || ”);
});

//check localStorage to prevent overwriting values, write values if empty
if (localStorage.getItem(‘brazosMC’) == null) {
localStorage.setItem(‘brazosMC’, JSON.stringify(result));
}
}
var elements = document.getElementsByClassName(“apply”);
var i = elements.length;
console.log(elements);
var params = JSON.parse(localStorage.getItem(‘brazosMC’));
console.log(params);

if (params !== null) {
if (“mc” in params) {
var url = “https://example.com/Account/Login?code=xxxx” + “&” + “mc=” + params.mc;
while (i–) {
elements[i].href = url;
console.log(elements[i].href);
}
} else {
console.log(“Key undefined”);
}
}

}
This works on our straight HTML site. A link such as www.example.com?mc=234 will store the key value mc 234 correctly. Then the code accurately finds links or buttons with the class name “apply” and replaces the HREF attribute.

However, upon converting the site to WordPress and loading the script, it no longer works. The url parameter object is successfully created and stored in localStorage and can be retrieved. But wordpress won’t let the javascript replace the HREF.

I say that, however, when I look at the link’s properties in the Console, the HREF attribute DOES have the marketing code appended, but the innerHTML property doesn’t have it.

I have added the following to the theme’s functions.php file so that it will recognize the query variable:

add_filter( ‘query_vars’, ‘add_query_vars_filter’ );
function add_query_vars_filter( $vars)
{
$vars[]=”mc”;
return $vars;
}

Any suggestions on why wordpress won’t allow me to rewrite the href property?

Read more here:: WordPress not allowing rewriting HREF with url parameters using Javascript?

Leave a Reply

Your email address will not be published. Required fields are marked *