How would i be able to put the follow on the end of every link of my website with out editing every link?
e.g www.WebsiteName/?ref=123
so if i went to www.WebsiteName/aboutus.php
i want it to add ?ref=123
onto the end of the url.
How would i be able to put the follow on the end of every link of my website with out editing every link?
e.g www.WebsiteName./?ref=123
so if i went to www.WebsiteName./aboutus.php
i want it to add ?ref=123
onto the end of the url.
- Keep in mind that of course the end user needs to have javascript enabled for any of these solutions to work. You could change the links server side using output buffering, and either phpquery or regex. – mellowsoon Commented Oct 21, 2010 at 22:23
4 Answers
Reset to default 8var has_querystring = /\?/;
$("a[href]").
each(function(el) {
if ( el.href && has_querystring.test(el.href) ) {
el.href += "&ref=123";
} else {
el.href += "?ref=123";
}
});
Depends on what you mean by without editing every link.
If you mean that you just don't want to manually add it in your source, you could do this:
$('a[href]').attr('href', function(i, hrf) { return hrf + '?ref=123';});
Or if you meant that you didn't want to have to do that, you could attach a .click()
handler that will add the value when the link is clicked.
$('a[href]').click(function( e ) {
e.preventDefault();
window.location = this.href + '?ref=123';
});
I would use a RewriteRule. It's the easiest and most reliable way in my opinion. That is to say not parsing the page with PHP or fighting DOM load issues with JavaScript
Here's an example:
# For blank query only
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)\.php$ /$1.php?ref=123 [L]
# Append to existing query
RewriteCond %{REQUEST_URI} \.php$
RewriteRule ^(.*)$ /$1&ref=123 [QSA,L]
$('a[href]').attr("href", function(){
this.href + '?ref=123';
});
Would be a very simple method. You'd probably have to add some error checking to make sure you're not ruining any other parameters, etc.