1

What is the best way to extract query parameters from Wordpress urls in javascript. Urls are pure permalinks without "?". The worpdress site is multilinugual (WPML), so the will be url varations. The same value has to be exctracted from different permalink equivalents.

example.com/location/1

example.com/de/lage/1

user1276919
  • 550
  • 5
  • 25

3 Answers3

2

You need window.location.search get query string.

You need window.location.pathname to get all data after first slash.

For example for this page:

> console.log(window.location.pathname);
/questions/43932650/how-to-extract-query-parameters-from-wordpress-permalinks-in-javascript/43932720#43932720

> console.log(window.location.search);
'' // becase there is no query string

After that you have to parse query string. You need this:

window.location.search.substr(1).split('&').map(function (value) {
  var data = value.split('=');
  return {
    param : data[0],
    value : data[1]
  }
});

For this tring

https://www.google.ru/search?q=javascript+location+get+parameters&oq=javascript+location+get+parameters&aqs=chrome..69i57j0l5.6512j0j7&sourceid=chrome&ie=UTF-8

the result will be:

enter image description here

Now, you need something similar to parse pathname. I don't know specific of how this string is built from WP side so I can't help there.

Sharikov Vladislav
  • 7,049
  • 9
  • 50
  • 87
  • Thank you, In my case there will be never query strings like ?q=1&param=1 , only premalinks /q/1/param/1 – user1276919 May 12 '17 at 08:43
  • Ye, I also provided the information how to get the string after `host:port`. Here is it `window.location.pathname`. I also said that you have to think about it by yourself based on information that I gave to you about query string. – Sharikov Vladislav May 12 '17 at 08:48
0

I ened with php solution:

   <?php  if( array_key_exists( 'location' , $wp_query->query_vars ) ):
       $l= $wp_query->query_vars["location"];?>
        <script type="text/javascript">
        window.qloc="<?php echo $l;?>";
        </script>
    <?php endif; ?>
user1276919
  • 550
  • 5
  • 25
0

Method 1: You can get all params as an array:

example URL: example.com?discount_code=1234

var urlParams = new URLSearchParams(window.location.search);

if(urlParams && urlParams.has('discount_code'))
{
   alert(urlParams.get('discount_code'));
}

Details of browser compatibility


Method 2: View This Answer

Sabrina
  • 2,531
  • 1
  • 32
  • 30