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

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("https://wordpress.stackexchange.com/" . $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:

Leave a Comment