Home > other >  Modifying URLs on a WP webpage depending on the incoming request URL parameters
Modifying URLs on a WP webpage depending on the incoming request URL parameters

Time:09-18

I have a specific task where I have to alter the URLs contained within a WP webpage, based on the parameter of the incoming URL request.

Let's say I have a webpage https://example.com/prefix, on that page, there are several links that point to another page, say https://example2.com/prefix

So whenever someone gets redirected to https://example.com/prefix with a certain URL parameter, let's say https://example.com/prefix?Layout=1, then that parameter would need to automatically get added to the existing links on the said page, so in this case https://example2.com/prefix links would turn into https://example2.com/prefix?Layout=1

Any ideas on how to go about this? Much appreciated.

CodePudding user response:

I hope I got your point correctly, there are many ways to do this but let me introduce a frontend way using JS & jQuery. let me write the solution and will explain it later.

var urlParams = new URLSearchParams(window.location.search);
var targetedParamValue = urlParams.get('test');
if (targetedParamValue !== null){
    $('a').each(function(index, item){
        var originalLink = $(item).attr('href'); // save the original link
        if (!originalLink) return; // check if it is not an empty href
        if(originalLink.search(/http/gi) === -1) return; // check if it is a valid link
        if(originalLink.search(/\?/g) === -1) {
            $(item).attr('href', originalLink   "?test="   targetedParamValue);
        } else {
            $(item).attr('href', originalLink   "&test="   targetedParamValue);
        }
    });
}

Basically, we:

  • Capture the param.
  • Capture anchor tags.
  • loop through each tag.
  • Check if we can apply the param to the anchor tags.
  • Append the param or add it.
  • Related