5

I have the permalink structure http://domain.com/%postname%/, which is what I want to keep for most of my posts, however there is one category of posts that I would like to move from http://domain.com/%postname%/ to http://domain.com/articles/%postname%/.

Any ideas how I can accomplish this for that one category of posts without changing the URLs of all the other posts?

  • 1
    Although you can do that (see @Dan's answer, I think it is correct), What you really need is a custom post type, I think. – cybmeta Jun 1 '16 at 5:28
  • If you need this also for all the normal post's rewrite rules (content pagination, feed, archive, ... ) then it's a good idea from @cybmeta to use a custom post type for articles otherwise you could check out the approach in Dan's answer. – birgire Jun 1 '16 at 8:14
  • I was going to suggest making the post type hierarchical so you could set a parent post, but having tried it... it still redirects /articles/%postname%/ back to /%postname%/ for reasons I have yet to fathom... I can't see any other difference in the post type objects for page and post. strange, anyone with clues on that? – majick Jun 7 '16 at 9:32
6
+25

Suppose articles is slug of the category.

1. Add a custom rewrite rule:

add_action('init', function()
{
    add_rewrite_rule('^articles/([^/]+)/?$', 'index.php?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 ( has_category('articles', $post) ) {
        $post_link = str_replace('/' . $post->post_name, '/articles/' . $post->post_name, $post_link);
    }

    return $post_link;

}, 10, 4);

That's all. Try it out in your functions.php and remember to flush your permalink structure.

References:

| improve this answer | |
  • 2
    I think you can simplify this further with a has_category() check, that's a wrapper for has_term( $category, 'category', $post ). There's also the old in_category() that's a wrapper for has_category(). – birgire Jun 1 '16 at 8:00
  • 1
    @birgire You rock! I have learnt from you a lot :) – SarahCoding Jun 1 '16 at 8:22
  • 2
    I'm just trying to pass on what I've learnt from this great community ;-) ps: just a note regarding the string replacement: if the post's slug is contained in the domain name then we will have a problem. – birgire Jun 1 '16 at 8:49
  • Thanks this worked. I changed domain.com/%postname% to domain.com/news/%postname%. But I am having issues with categories under NEWS itself. How can I make this work for sub-categories – Samuel Afolabi Jan 18 '18 at 21:09

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