A user will be directed from a website to a landing page that will have a query string in the URL i.e. www.sitename.com?foo=bar&bar=foo. What I want to do, is then append that query string to all links on the page, preferably whether they were generated by WordPress or not (i.e. hard coded or not) and done server-side.

The reason for this is because their goal destination has to have the query string in the URL. I could use cookies, but i'd rather not since it has many other problems that it will bring with it for my specific use case.

I have explored the possibility of using .htaccess in conjunction with $_SERVER['QUERY_STRING'] to no avail. My understanding of .htaccess isn't great, but in my mind I assumed it would be possible to rewrite the current URL to be current URL + the variable that stores $_SERVER['QUERY_STRING'].

I've also explored add_rewrite_rule but couldn't find a logical way to achieve what I want.

Here's the Javascript solution I have, but as I said, I'd like a server-side solution:

const links = document.querySelectorAll('a');

links.forEach(link => {

        if (!link.host.includes(location.host)) {

    const url = new URL(link.href);

    const combined = Array.from(url.searchParams.entries()).reduce((agg, [key, val]) => {
        agg.set(key, val);
        return agg;
}, (new URL(location.href)).searchParams);

    const nextUrl = [link.protocol, '//', link.host, link.pathname].join('');

    link.href = (new URL(`${nextUrl}?${combined.toString()}`)).toString();
  • i guess a server side solution isn't appropriate as you could not cache your website anymore.. – André Kelling Jan 8 '19 at 13:12
  • 1
    I'm not sure I understand the reasoning behind doing this, are you trying to implement a tracker? Keep in mind you need the users consent in many countries to be able to collect their information – Tom J Nowell Jan 8 '19 at 13:45
  • BTW you can’t use .htaccess in this way. If user goes to the site with your querystring and clicks on any link (that has no querystring), then he’ll go to that new link and it will cause new request - so server won’t know the querystring anymore... – Krzysiek Dróżdż Jan 8 '19 at 13:49
  • @TomJNowell I'm taking that query string and submitting it via form, which is then posted via API in to an external excel-like sheet. The query string is created by the original website and is dynamic, so I want to capture the details of that query string for informational purposes. Luckily there is no personally identifiable information, so GDPR isn't an issue. – Nikki Mather Jan 8 '19 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.