最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugins - Add rewrite rule to permalink structure

programmeradmin2浏览0评论

I have a Custom Structure setup for posts in Settings > Permalinks as:

/%category%/%post_id%-%postname%

This works great for most of my posts, but there is one category that I want to remove the post_id from so it looks like this:

/%category%/%postname%

So if the category is MOUSE and the post-id is 123 and postname(slug) is my-great-mouse-post, then the permalink correctly looks like this:

mydomain/mouse/123-my-great-mouse-post

But if the category is DOG then I do not want the post-id, so it should look like this:

mydomain/dog/my-great-dog-post

I understand how to use actions and filters in my functions.php and in a plugin and I think I want to use add_rewrite_rule but am honestly confused as how to write the rule as regex is complicated and I do not understand it.

I have a Custom Structure setup for posts in Settings > Permalinks as:

/%category%/%post_id%-%postname%

This works great for most of my posts, but there is one category that I want to remove the post_id from so it looks like this:

/%category%/%postname%

So if the category is MOUSE and the post-id is 123 and postname(slug) is my-great-mouse-post, then the permalink correctly looks like this:

mydomain/mouse/123-my-great-mouse-post

But if the category is DOG then I do not want the post-id, so it should look like this:

mydomain/dog/my-great-dog-post

I understand how to use actions and filters in my functions.php and in a plugin and I think I want to use add_rewrite_rule but am honestly confused as how to write the rule as regex is complicated and I do not understand it.

Share Improve this question edited Jun 5, 2016 at 12:49 jsherk asked Jun 1, 2016 at 23:32 jsherkjsherk 1873 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 4

1. Add a new rewrite rule:

add_action('init', function()
{
    add_rewrite_rule('^dog/([^/]+)/?$', 'index.php?cat=dog&name=$matches[1]', 'top');
}, 10, 0);

2. Filter the post link:

add_filter('post_link', function($post_link, $post, $leave_name = false, $sample = false)
{
    if ( is_object_in_term($post->ID, 'category', 'DOG') ) {
        $post_link = str_replace($post->ID . '-', '', $post_link);
    }

    return $post_link;

}, 10, 4);

Try it in your functions.php. Hope it works for you!

发布评论

评论列表(0)

  1. 暂无评论