假设我想为URL添加永久链接:site.com/section/{postname}
“section”与一篇文章的类别名称相匹配(仅针对一个案例)。在花点时间研究文档之后。我为rewrite\\u url添加了一个函数。在“函数”中。我的模板(Astra)的php文件。对于我在末尾添加的内容:
add_action( \'init\', \'wpa_rewriterules\' );
function wpa_rewriterules()
{
add_rewrite_rule(
// The regex to match the incoming URL
\'section/([^/]+)/?\',
// The resulting internal URL: `index.php` because we still use WordPress
\'index.php?name=$matches[1]\',
\'top\' );
}
我还读到,我必须以同样的方式向“the\\u permalink”添加一个过滤器,以便每次必须显示链接时,它都会转换为所需的URL。因此,我在相同的“函数”中添加了该过滤器的代码。php文件:
add_filter(\'the_permalink\', \'post_permalink_w_seccion\');
function post_permalink_w_seccion( $link ) {
global $post;
$postcat = get_the_category( $post->ID );
if ( $post->post_type === \'post\' && $postcat->slug == \'section\') {
$link = str_replace( $post->post_name, \'section/\' . $post->post_name, get_permalink( $post ) );
}
return $link;
}
但是
this is what does not work for me. URL不会转换或更改。你能帮我看看我做错了什么或错过了什么吗?
而且,我不确定这是否是我想要的最好的方式。我对Wordpress这个世界还不熟悉。
P、 我总是保存对“永久链接”的更改,以刷新URL规则。
非常感谢。
最合适的回答,由SO网友:nmr 整理而成
作用get_the_category()
返回数组,这就是条件$postcat->slug == \'section\'
始终是false.
在当前表单中,过滤器可以更改指向没有section
类别您应该更改函数以检查get_permalink()
调用,而不是检查global $post
.
add_filter( \'post_link\', \'post_permalink_w_section\', 10, 2 );
function post_permalink_w_section( $link, $post )
{
if ( $post->post_type === \'post\' && has_category(\'section\', $post) )
{
$link = str_replace( $post->post_name, \'section/\' . $post->post_name, $link );
}
return $link;
}