在pl_custom_rewrite_rules()
函数,将REGEX模式更改为^new_slug/(.*)$
例如:
add_rewrite_rule( \'^new_slug/(.*)$\', \'index.php?name=$matches[1]\', \'top\' );
因为WordPress删除了前面的
/
从请求路径(
WP::$request
), 所以使用
^/new_slug
从不计算为
true
.
此外,在pl_custom_permalink()
功能,移除global $post;
因为函数已经接收到正确的post数据(即。$post
) 如中所示function pl_custom_permalink( $permalink, $post, $leavename )
.
我使用的完整代码,没有任何重新缩进:(在WordPress 4.9.8上进行了尝试和测试)
add_filter( \'post_link\', \'pl_custom_permalink\', 10, 3 );
function pl_custom_permalink( $permalink, $post, $leavename ) {
if ( has_category( \'My Category\', $post->ID) ) {
$permalink = trailingslashit( home_url(\'/new_slug/\'. $post->post_name . \'/\' ) );
}
return $permalink;
}
add_action(\'init\', \'pl_custom_rewrite_rules\');
function pl_custom_rewrite_rules( $wp_rewrite ) {
add_rewrite_rule( \'^new_slug/(.*)$\', \'index.php?name=$matches[1]\', \'top\' );
}
以下是规范重定向的代码
example.com/name-of-my-post
到
example.com/new_slug/name-of-my-post
:
add_action( \'wp\', function( $wp ){
// If it\'s a single Post and it\'s in the \'My Category\' category, redirect to
// the canonical version. Also check if the request path doesn\'t start with
// new_slug/ as in http://example.com/new_slug/hello-world/
if ( ! preg_match( \'#^new_slug/#\', $wp->request ) &&
is_singular() && in_category( \'My Category\' ) ) {
wp_redirect( get_permalink() );
exit;
}
} );