URL重写WordPress页面查询字符串

Ont*_*toz 2 php wordpress .htaccess mod-rewrite url-rewriting

我有一个WordPress网站,其自定义页面比较获取一个字符串.

现在需要:

mysite.com/phones/compare/?between=samsung-galaxy-note-3-vs-nokia-lumia-730
Run Code Online (Sandbox Code Playgroud)

它必须是这样的:

mysite.com/phones/compare/samsung-galaxy-note-3-vs-nokia-lumia-730
Run Code Online (Sandbox Code Playgroud)

我已经尝试在我的网站上添加代码.htaccess但这对我没用,并转到WordPress 404页面:

RewriteRule ^phones/compare/(.+?)/?$ phones/compare/?between=$1 [NC,L]
Run Code Online (Sandbox Code Playgroud)

此外,当用户访问mysite.com/phones/compare/?between=URL时,我也需要重定向到新的搜索引擎友好URL.

Ana*_*hah 7

你得到一个404页面,因为WordPress内部不了解如何处理URL.因此,您正在寻找的解决方案将是.htaccess(用于重定向)和重写规则的组合,以便WordPress可以处理URL

将以下内容添加到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' );
}
Run Code Online (Sandbox Code Playgroud)

替换XXX为比较页面的page_id,通过重新保存永久链接结构来刷新重写规则.现在为.htaccess添加规则以进行重定向,这应该有效.

编辑

将以下代码添加到functions.php以访问between页面中的查询var

add_filter('query_vars', 'my_query_vars', 10, 1);

function my_query_vars($vars) {
    $vars[] = 'between'; 
    return $vars;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它来访问它 get_query_var("between")