WordPress 页面查询字符串上的 URL 重写 [英] URL Rewrite on a WordPress Page Query String
问题描述
我有一个带有自定义页面比较的 WordPress 网站,可以获取一个字符串.
I have a WordPress site with a custom page comparison that gets a string.
现在需要:
mysite.com/phones/compare/?between=samsung-galaxy-note-3-vs-nokia-lumia-730
应该是这样的:
mysite.com/phones/compare/samsung-galaxy-note-3-vs-nokia-lumia-730
我尝试在我网站的 .htaccess 上添加对我不起作用的代码并转到 WordPress 404 页面:
I've tried adding code on my site's .htaccess that didn't worked for me and went to WordPress 404 page:
RewriteRule ^phones/compare/(.+?)/?$ phones/compare/?between=$1 [NC,L]
此外,当用户访问 mysite.com/phones/compare/?between= URL 时,我也需要重定向到新的搜索引擎友好 URL.
Also I need to redirect to the new search engine friendly URL too when user gets to mysite.com/phones/compare/?between= URL.
推荐答案
您得到 404 页面是因为 WordPress 内部不了解如何处理 URL.因此,您正在寻找的解决方案将是 .htaccess(用于重定向)和重写规则的组合,以便 WordPress 可以处理 URL
You are getting a 404 page because WordPress internally doesn't understand how to handle the URL. So the solution you are looking for will be a combination of .htaccess (for the redirection) plus a rewrite rule so that WordPress can handle the URL
在functions.php中添加以下内容
Add the following to functions.php
add_action( 'init', 'init_custom_rewrite' );
function init_custom_rewrite() {
add_rewrite_rule(
'^phones/compare/([^/]*)/?',
'index.php?page_id=XXX&between=$matches[1]',
'top' );
}
将 XXX
替换为比较页面的 page_id,通过重新保存永久链接结构来刷新重写规则.现在向 .htaccess 添加一条规则以进行重定向,这应该可以工作.
Replace XXX
with the page_id of compare page, flush the rewrite rules by re-saving your permalink structure. Now add a rule to .htaccess for the redirection and that should work.
在functions.php中加入如下代码,访问页面中between
查询变量
Add the following code to functions.php to access between
query var in the page
add_filter('query_vars', 'my_query_vars', 10, 1);
function my_query_vars($vars) {
$vars[] = 'between';
return $vars;
}
然后您可以使用 get_query_var("between")
这篇关于WordPress 页面查询字符串上的 URL 重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!