in my site i have many category and subcategory (child category)

say like my one category name

- 4 color
- 2 color
- offset print

Exmple i want when visit 4 color category page it will show all 4 color category post with particular template. i tried many code but not is actually give me perfect result. bellow is one which is used it is work nice but now issue is it also effect on other category child also.

add_action('template_redirect', 'load_category_tree_template');
function load_category_tree_template() {
        if (is_category() && !is_feed()) {
            // replace 'your-base-category-slug' with the slug of root category
            $base_tree_cat_id = get_cat_id('printing-products'); 
                // get current category id
            $catid = get_query_var('cat'); 

            if (is_category($base_tree_cat_id) || cat_is_ancestor_of($base_tree_cat_id, $catid)) {
                load_template(STYLESHEETPATH . 'category-printing.php');

1 Answer 1


Don't use template_redirect to load alternate templates as you can break any functionality that uses this hook to run on a lower priority than yours. The right hook is template_include. This is according to Mark Jaquith, one of the WP lead developers. https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/

That said, it might be more appropriate to use the category_template filter in this case.

I use this, based on a code snippet I found and badly didn't keep a note of the source :-(

function wpse_233263_parent_category_hierarchy() {
    $templates = array();
    $category = get_queried_object();

    if ( $category->category_parent != 0 ) {
        $parent = get_category( $category->category_parent );

        if(!empty($parent)) {
            $templates[] = "category-{$parent->slug}-{$category->slug}.php";
            $templates[] = "category-{$parent->slug}.php";
            $templates[] = "category-{$parent->term_id}.php";
    } else {
        // Otherwise use the usual default category template files
        $templates[] = "category-{$category->slug}.php";
        $templates[] = "category-{$category->term_id}.php";

    $templates[] = 'category.php';

    return locate_template( $templates );

add_filter( 'category_template', 'wpse_233263_parent_category_hierarchy' );

It fires when a category template is called for and essentially sets up one list of templates if you're in a child category or sets up the default list if not.

In a child category you can have a template category-parent_slug-child_slug.php and if that doesn't exist fall back to the parent. Tweak the list to suit your needs.

  • No problem - if it suits your needs then please do accept the answer & vote :-) Commented Jul 26, 2016 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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