5

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.com/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.com/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.

1 Answer 1

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!

5
  • You are a genius. I spent hours and hours trying to figure this out. Works great. I added flush_rewrite_rules(); in the add_rewrite_rules function as I am using this in a plugin, but otherwise was perfect.
    – jsherk
    Jun 2, 2016 at 2:18
  • And just a side note, I found a great REGEX tester here: regex101.com which let me figure out what exactly ^dog/([^/]+)/?$ was doing. The only caveat with this tester is you have escape the slashes like this: ^dog\/([^\/]+)\/?$
    – jsherk
    Jun 2, 2016 at 2:24
  • 2
    @jsherk - only use flush_rewrite_rules when your plugin is activated, don't flush on every request! read the usage note in the codex for more info.
    – Milo
    Jun 2, 2016 at 3:01
  • @Milo I just was reading that before I saw your comment, and was coming back to post exactly what you said. Thanks.
    – jsherk
    Jun 2, 2016 at 3:12
  • Some good related info in this other thread: wordpress.stackexchange.com/questions/228538/…
    – jsherk
    Jun 5, 2016 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.