场景如下:我编写了一个自定义url规则,将注释id传递给模板,并将注释和注释元显示为单个页面(eg. http://example.com/reply/56
) 而且效果很好。但现在我正试图完善这条规则,以便在URL中包含评论帖子slug。所以当我访问\'http://example.com/reply/56\'
它应该映射到\'http://example.com/the-post/reply/56\'
. 我实际上被困在这一点上了。以下是我迄今为止所做的:有效的规则:
<?php
add_rewrite_rule( \'^reply/(.*)?$\', \'index.php?pagename=reply-page&reply_id=$matches[1]\', \'top\' );
?>
添加了
query_var
\'reply_id\'
为了这个。
现在,我正在尝试的代码是:
<?php
add_action(\'init\', \'test\');
function test()
{
$reply_struct = \'/reply/%reply_id%\';
$wp_rewrite->add_rewrite_tag(\'%reply_id%\', \'([^/]+)\', \'reply_id=$matches[1]\');
$wp_rewrite->add_permastruct(\'reply_id\', $reply_struct, false);
}
add_filter(\'post_type_link\', \'reply_permalink\', 10, 3)
function reply_permalink()
{
$rewritecode= array(
\'%reply_id%\'
);
$test = \'\';
if ( strpos($permalink, \'%reply_id%\') !== false )
{
$i = get_query_var(\'reply_id\'); //Trying to get the comment id, this is where I\'ll get the post slug and append it to the url
$test = \'test\';
}
$rewritereplace = array(
$test
);
$permalink = str_replace($rewritecode, $rewritereplace, $permalink);
return $permalink;
}
我想当我访问URL时
\'http://example.com/reply/56\'
, 我应该
\'http://example.com/test/\'
或
\'http://example.com/reply/test\'
. 但我不是。
最合适的回答,由SO网友:chrisguitarguy 整理而成
除非你声明$wp_rewrite
作为测试函数中的全局变量,您将尝试访问局部变量$wp_rewrite
. 这当然行不通。
添加行global $wp_rewrite;
:
<?php
add_action(\'init\', \'test\');
function test()
{
global $wp_rewrite;
$reply_struct = \'/reply/%reply_id%\';
$wp_rewrite->add_rewrite_tag(\'%reply_id%\', \'([^/]+)\', \'reply_id=$matches[1]\');
$wp_rewrite->add_permastruct(\'reply_id\', $reply_struct, false);
}