Give specific category its own permalink structure

For the purposes of my site, I have my Permalinks set to /blog/%postname%/ for all posts.

However, I need to give Posts with a specific Category (in this case, “Testimonials”) its own permalink structure, where each individual post assigned the Category “Testimonials” returns as /testimonials/%postname%/ and the Category Archive page returns as /testimonials/.

Here is the code I have so far:

//Rewrite URLs for “testimonial” category
add_filter( ‘post_link’, ‘custom_permalink’, 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
// Get the category for the post
$category = get_the_category($post->ID);
if ( !empty($category) && $category[0]->cat_name == “Testimonials” ) {
$cat_name = strtolower($category[0]->cat_name);
$permalink = trailingslashit( home_url(‘/’. $cat_name . ‘/’ . $post->post_name .’/’ ) );
}
return $permalink;
}

add_action( ‘init’, ‘custom_rewrite_rules’ );
function custom_rewrite_rules() {
add_rewrite_rule(
‘testimonials/([^/]+)(?:/([0-9]+))?/?$’,
‘index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]’,
‘top’ // The rule position; either ‘top’ or ‘bottom’ (default).
);
}

This successfully returns each individual post with the category “Testimonials” as /testimonials/%postname%/. However, the Category Archive page returns as /blog/category/testimonials. I need this to just return as /testimonials/, while still returning all other Posts as /blog/%postname%/

I tried using this plugin, https://wordpress.org/plugins/custom-permalinks/, which solved the Category Archive page issue, but broke each individual testimonial post, returning them as a 404 error.

In this case, I cannot register Testimonials as a Custom Post Type as it will affect other site functionality,

Read more here:: Give specific category its own permalink structure

Leave a Reply

Your email address will not be published. Required fields are marked *