I have a blog in WordPress. I have multiple categories. I want to use a specific layout for all posts under a category and all of its sub categories.

Example : My categories organized as bellow.

  1. Guide(parent category)

    1.1 Electical

    1.1.1 TV

    1.1.2 Radio

    1.2 Plumbing

    1.3 Home Repair

    1.3.1 Kitchen

    1.3.2 Bathroom

2 Answers
2

You can do that with single_template filter. First you will need to check if a post belongs to a top level category. So here is the function.

// custom single template for specific category
function wpse_custom_category_single_template( $single_template ) {

    global $post;

    // get all categories of current post
    $categories = get_the_category( $post->ID );
    $top_categories = array();

    // get top level categories
    foreach( $categories as $cat ) {
        if ( $cat->parent != 0 ) {
            $top_categories[] = $cat->parent;
        } else {
            $top_categories[] = $cat->term_id;
        }
    }

    // check if specific category exists in array
    if ( in_array( '8', $top_categories ) ) {
        if ( file_exists( get_template_directory() . '/single-custom.php' ) ) return get_template_directory() . '/single-custom.php';
    }

    return $single_template;

}

add_filter( 'single_template', 'wpse_custom_category_single_template' );

In similar situation usually people check for parent category with $categories[0]->category_parent;, which is right but only works if you have assigned one category to each post. If you have 2 and more categories then this solution will always work.

Leave a Reply

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