简体   繁体   English

如何从要在 javascript 中使用的 wordpress 永久链接中提取查询参数?

[英]How to extract query parameters from wordpress permalinks to be used in javascript?

What is the best way to extract query parameters from Wordpress urls in javascript.从 javascript 中的 Wordpress url 中提取查询参数的最佳方法是什么。 Urls are pure permalinks without "?".网址是没有“?”的纯永久链接。 The worpdress site is multilinugual (WPML), so the will be url varations. worpdress 站点是多语言 (WPML),因此将是 url 变量。 The same value has to be exctracted from different permalink equivalents.必须从不同的永久链接等价物中提取相同的值。

example.com/location/1 example.com/location/1

example.com/de/lage/1 example.com/de/lage/1

You need window.location.search get query string.您需要window.location.search获取查询字符串。

You need window.location.pathname to get all data after first slash.您需要window.location.pathname在第一个斜杠后获取所有数据。

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:结果将是:

在此处输入图片说明

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.我不知道这个字符串是如何从 WP 端构建的,所以我无能为力。

I ened with php solution:我使用了 php 解决方案:

   <?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; ?>

Method 1: You can get all params as an array:方法1:您可以将所有参数作为数组获取:

example URL: example.com?discount_code=1234示例网址: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方法 2:查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM