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.

1 Answer
1

Try these steps:

Step #1: Replace this:

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;
}

..with this one:

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).
    );
}

Step #2: Go to the Permalink Settings page, and click on the Save Changes button without actually making any changes.

Leave a Reply

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