Steve
Steve

Reputation: 11

Add a parameter to every link in my wordpress website

I want to add a parameter to every link in my website, let's say ?var=123 .

I tried to use those codes but nothing happened:

var has_querystring = /\?/; 

$("a[href]").each(function(el) {
    if ( el.href && has_querystring.test(el.href) ) {
        el.href += "&var=123";
    } else {
        el.href += "?var=123";
    }
});

$('a[href]').attr('href', function(i, hrf) { return hrf + '?var=123';});

$('a[href]').click(function(e) {
    e.preventDefault();
    window.location = this.href + '?var=123';
});`

What am I doing wrong? Thank you.

Upvotes: 0

Views: 68

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

If none of those worked then it sounds like your jQuery code is executing before the DOM has finished being constructed, and it's not selecting any of the elements. The solution to that is to use a DOM ready event handler:

$(document).ready(function() {
    // your code here
});

In the case of the first snippet, using .each(), note that the first argument passed to the function is the index of the element, not the element itself, so you actually want:

$('a[href]').each(function(index, el) {
    ...
});

Upvotes: 1

Related Questions