通过Wordpress中的URL传递多个参数

时间:2018-03-20 11:34:52

标签: php wordpress forms get arguments

在我的主页上,我有一个带有三个下拉框的表单。单击提交按钮后,我通过GET请求将表单参数发送到服务器,然后重定向到search-results.php页面以显示基于这三个参数的搜索结果。我需要在URL中包含参数,以防用户想要通过复制和粘贴URL来重现搜索。我的问题是,当搜索结果页面加载时,只有第一个参数显示在URL中,当我重新加载页面时,只能在服务器中检索该参数。我已经启用了很多永久链接,但禁用它没有任何区别。

以下是我的表单代码:

$url = add_query_arg(array(
  'param1' => $_GET['param1'],
  'param2' => $_GET['param2'],
  'param3' => $_GET['param3'],
), get_permalink(get_page_by_path('search-results')));  

if(wp_redirect($url)) {
  exit;
}

然后,在服务器上,我收到包含所有参数的GET请求,处理搜索,然后重定向到搜索结果页面:

add_filter('query_vars', function($vars) {
  $vars[] = "param1";
  $vars[] = "param2";
  $vars[] = "param3";
  return $vars;
});

我通过添加以下过滤器告诉Wordpress接受这些参数:

www.mysite.com/search-results/?param1=1

当搜索结果页面加载正确的数据时,URL为:

{{1}}

param2和param3只是消失了。复制和粘贴此URL将加载没有参数的页面。

我正在尝试找到解决此问题的方法。有没有人有任何想法?我做错了吗?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我弄明白了什么。我还需要添加一个重写规则来将带有GET参数的URL转换成我想要的:

/**
 * Add a rewrite rule to accept GET arguments on the search results page
 */
add_filter('init', function() {
  add_rewrite_rule(
    // The resulting URL with regex to match the incoming arguments
    'search/([^/]*)/([^/]*)/([^/]*)/?',
    // The expected URL
    'index.php?pagename=search-results&param1=$matches[1]&param2=$matches[2]&param3=$matches[3]',
    // This is a rather specific URL, so we add it to the top of the list
    // Otherwise, the "catch-all" rules at the bottom (for pages and attachments) will "win"
    'top' );
});

换句话说,当Wordpress收到页面的搜索结果'包含param1 = 1,param2 = 2和param3 = 3,它将其转换为以下URL:

www.mysite.com/search-results/1/2/3/