Displaying custom template for specific categories

I have a “Program” category and this category have childs. (For example Program -> Improving speed )

I want to display custom category template for childs of Program category.

Read More

I found that :
WordPress have template_include function that executes immediately before WordPress includes the predetermined template file. This can be used to override WordPress’s default template behavior.

So I try to use this code in my functions.php file :

function wpse_template_check( $template ) {
    if ( is_category() ) {
        // Get category information
        $cat = get_query_var( 'cat' ); 
        // read the category parent 
        $parent_category = $cat->category_parent;

        //I want to load this template
        $new_template = locate_template( array( 'category-program.php' ) );

        //Program category have ID=43 so I check here if parent category = program 
        if ( ($parent_category) == 43) {
            return $new_template;
        }
    }
    return $template;
}
add_filter( 'template_include', 'wpse_template_check' );

But it did not work…

Related posts

Leave a Reply

1 comment

  1. EDIT

    The issue here is that get_query_var( 'cat' ) returns the current category ID. If you had debug turned on, you would have seen the following notice

    NOTICE Error: [8] Trying to get property of non-object

    You should replace get_query_var( 'cat' ) with get_queried_object() which will get the queried object object.