有不同的方法可以达到这个效果,我使用pre_post_link
和post_rewrite_rules
过滤器挂钩。
你可以使用eg。generate_rewrite_rules
挂钩,但带有post_rewrite_rules
, 您可以轻松地将永久链接不仅更改为帖子,还可以更改为其评论、附件等。您可以保留或替换为新的永久链接。
添加以下代码后,单击Save 在里面Dashboard -> Settings -> Permalinks
.
add_filter(\'pre_post_link\', \'se332921_pre_post_link\', 20, 3);
add_filter(\'post_rewrite_rules\', \'se332921_post_rewrite_rules\');
/**
* @param string $permalink The site\'s permalink structure.
* @param WP_Post $post The post in question.
* @param bool $leavename Whether to keep the post name.
*/
function se332921_pre_post_link($permalink, $post, $leavename)
{
if ( $post instanceof WP_Post && $post->post_type == \'post\')
$permalink = \'/post-prefix\'.$permalink;
return $permalink;
}
/**
* @param array $post_rewrite The rewrite rules for posts.
*/
function se332921_post_rewrite_rules($post_rewrite)
{
if ( is_array($post_rewrite) )
{
$rw_prefix = [];
foreach( $post_rewrite as $k => $v) {
$rw_prefix[ \'post-prefix/\'.$k] = $v;
}
//
// merge to keep original rules
$post_rewrite = array_merge($rw_prefix, $post_rewrite);
//
// or return only prefixed:
// $post_rewrite = $rw_prefix;
}
return $post_rewrite;
}