admin管理员组文章数量:1434924
I would like to set a permalink structure with a prefix that will appear just on the posts. The prefix should only be displayed for the posts and not for the permalinks of categories or tags.
I set the permalink structure as /post/%post_id%
and the post URL is example/post/12345
. But the prefix added also to the categories and tags and it become example/post/category/news
instead of example/category/news
. How I can do it?
I would like to set a permalink structure with a prefix that will appear just on the posts. The prefix should only be displayed for the posts and not for the permalinks of categories or tags.
I set the permalink structure as /post/%post_id%
and the post URL is example/post/12345
. But the prefix added also to the categories and tags and it become example/post/category/news
instead of example/category/news
. How I can do it?
1 Answer
Reset to default 1There are different ways to achieve this result, I used
pre_post_link
and post_rewrite_rules
filter hooks.
You can use eg. generate_rewrite_rules
hook, but with post_rewrite_rules
,
you can easily change permalinks not only to the post but also to its comments, attachments, etc.
Original permalinks you can keep or replace with new ones.
After adding the following code click Save in 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;
}
本文标签: Custom permalink structure with a prefix just for posts
版权声明:本文标题:Custom permalink structure with a prefix just for posts 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745629526a2667184.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论