Variable by URL in all page links

2

I'm using the following code to pass variables through the URL, in wordpress.

if (isset($_GET['layout'])) {
    $layout = $_GET['layout'];
} else {
    $layout = '1';
}

With $layout I retrieve the value in the code, where I use to change the layout style.

Calling this url works fine. localhost / wp /? layout = 2

In this url there are several links to other posts, pages, categories, etc. I would like that when calling a variable in the URL, it would apply to all links on that page.

For example: I start by calling the variable layout in the url so: localhost / wp /? layout = 2

And on this page you will have a link to the "about" page: so: localhost / wp / about

I wanted the layout variable to be automatically placed on it and all other links.

In this way: localhost / wp / about /? layout = 2 , localhost / wp / other-page /? layout = 2 , localhost / wp / category / technology /? layout = 2

    
asked by anonymous 19.02.2018 / 18:49

1 answer

1

With PHP I find it hard to do this. But with JavaScript you can change all the links.

The code below checks whether the layout variable exists in the URL. If it exists, add it and its value to all <a> links of the page:

var url_ = new URL(location.href),
    var_ = url_.searchParams.get("layout");
if(var_){
   var a_ = document.body.querySelectorAll("a");
   for(var x=0; x<a_.length; x++){
      a_[x].href += (a_[x].href.indexOf("?") == -1 ? "?" : "&")+"layout="+var_;
   }
}

Because the searchParams method is not supported in IE, it follows an alternative form:

var url_ = location.href,
    param = url_.indexOf("layout");
if(param != -1){
   var var_ = url_.substring(param+7,url_.length).match(/^(\d|\w){1,}/)[0],
       a_ = document.body.querySelectorAll("a");
   for(var x=0; x<a_.length; x++){
      a_[x].href += (a_[x].href.indexOf("?") == -1 ? "?" : "&")+"layout="+var_;
   }
}

Edit

To check multiple variables and apply to links, you can insert the names you want to manipulate into an array:

var url_ = location.href,
    param = url_.substring(url_.lastIndexOf("/"), url_.length),
    params = ['layout','teste']; // insira aqui os nomes das variáveis
for(var y=0; y<params.length; y++){
   if(param.indexOf(params[y]) != -1){
      var var_ = url_.substring(url_.indexOf(params[y])+params[y].length+1,url_.length).match(/^(\d|\w){1,}/)[0],
          a_ = document.body.querySelectorAll("a");
      for(var x=0; x<a_.length; x++){
         a_[x].href += (a_[x].href.indexOf("?") == -1 ? "?" : "&")+params[y]+"="+var_;
      }
   }
}
                                    
19.02.2018 / 19:50