The question:
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?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
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