How to rewrite Url under specific category in wordpress

Question

I am new in This platform and I have a website on WordPress and I want to create a blog on this website.

My permalink is – example.com /%postname%/

I want to rewrite Url under only this specific category like this: (blog is a category)

example.com/blog/ 
example.com/blog/subcategory/ (if has subcategory)
example.com/blog/postname/

I tried below code, it’s working without a subcategory

    //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]->slug == "blog" ) {
        $cat_name = strtolower($category[0]->slug);
        $permalink = trailingslashit( home_url('/'. $cat_name . '/' . $post->post_name .'/' ) );
    }
    return $permalink;
}

add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
    add_rewrite_rule(
        'blog/([^/]+)(?:/([0-9]+))?/?$',
        'index.php?category_name=blog&name=$matches[1]&page=$matches[2]',
        'top' // The rule position; either 'top' or 'bottom' (default).
    );
}
0
, ranbir 8 months 0 Answers 101 views 0

Leave an answer