Add a URL prefix to permalinks of one category of posts only

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x