php - Append query string to all URL's

admin2025-06-04  40

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?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)) {
        return;
    }

    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();
});
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749033121a315791.html

最新回复(0)