在我的主页上,我有一个带有三个下拉框的表单。单击提交按钮后,我通过GET请求将表单参数发送到服务器,然后重定向到search-results.php页面以显示基于这三个参数的搜索结果。我需要在URL中包含参数,以防用户仅通过复制和粘贴URL来重现搜索。我的问题是,当加载搜索结果页面时,URL中仅显示第一个参数,而当我重新加载页面时,只能在服务器中检索该参数。我启用了相当多的永久链接,但禁用它并没有任何区别。
这是我的表格的代码:
<form action="{{ esc_url( admin_url( 'admin-post.php' )) }}" method="GET">
<input name="action" type="hidden" value="form_response">
<select name="param1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="param2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="param3">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button type="submit" name="search_button">Search</button>
</form>
然后,在服务器上,我收到带有所有参数的GET请求,处理搜索,然后重定向到搜索结果页面:
$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;
}
我通过添加以下过滤器来告诉Wordpress接受参数:
add_filter('query_vars', function($vars) {
$vars[] = "param1";
$vars[] = "param2";
$vars[] = "param3";
return $vars;
});
当搜索结果页面加载正确的数据时,URL为:
www.mysite.com/search-results/?param1=1
param2和param3只是消失了。复制并粘贴此URL将加载不带参数的页面。
我正在尝试找到解决此问题的方法。有人有什么想法吗?我做错什么了吗?
任何帮助是极大的赞赏!
我找出了缺少的东西。我还需要添加一个重写规则,以将带有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¶m1=$matches[1]¶m2=$matches[2]¶m3=$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收到针对包含参数1 = 1,参数2 = 2和参数3 = 3的页面“搜索结果”的GET请求时,它将其转换为以下URL:
www.mysite.com/search-results/1/2/3/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句