1

I want to use different template for posts of all subcategory of one category. Below is the Code I am using :

add_filter( 'single_template', 'get_custom_cat_template' ) ;
function get_custom_cat_template( $single_template ) {
    global $post;
    if ( is_category( 'blog' ) || in_category( 'blog' ) ) {
        $single_template = dirname( __FILE__ ) . '/single-blog.php';
    }

    return $single_template;
}

Here "blog" is the category. This code is working for parent category (blog) only. For posts of subcategory, it is loading default single.php file.

How can I change the code so that it works for all subcategories of parent category?

3

You can check if current category is a child of blog category with cat_is_ancestor_of() function or term_is_ancestor_of(), or maybe better, use in_category(), as you are currently doing, but checking child categories as well.

add_filter( 'single_template', 'get_custom_cat_template' ) ;
function get_custom_cat_template( $single_template ) {


    // You want to filter only template for single posts of default post type    
    if( is_singular( 'post' ) ) {

        $post = get_queried_object();
        // Replace '3' with the ID of the 'blog' category
        $child_blog_categories = get_term_children( '3', 'category' );

        if ( in_category( 'blog', $post ) || in_category( $child_blog_categories, $post ) ) {

            $single_template = locate_template( 'single-blog.php' );

        }

    }

    return $single_template;
}

Anyway, I think that if you see yourself creating a category of posts to manage posts whithin that category in a different way, you may want to check out custom post types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.