A special single page templates for posts under a category and all its child category

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 Comment