My Custom Structure is set to “/blog/%postname%/”
This works as expected, but for Posts with the Category “testimonials”, I would like to change the URL structure to be “/testimonials/%postname%/”.
I put the following code in my functions.php
:
//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("https://wordpress.stackexchange.com/". $cat_name . "https://wordpress.stackexchange.com/" . $post->post_name ."https://wordpress.stackexchange.com/" ) );
}
return $permalink;
}
add_action('generate_rewrite_rules', 'custom_rewrite_rules');
function custom_rewrite_rules( $wp_rewrite ) {
$regex = '/[\s\S]/';
$new_rules = array(
trailingslashit('testimonials/'.$regex) => '/?p='. get_page_by_path('$matches[1]', OBJECT, 'post')->id
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
return $wp_rewrite;
}
This generates the desired URL, “myurl.com/testimonials/post-name” when I try to click on the desired Post, but then it returns a 404 error.
I’d like to accomplish the URL rewrite without needing to register a new Custom Post Type.