Apply custom category template to subcategories

Hello on my wordpress site I have a custom template for category A with slug (cat-a). I created a category-cat-a.php file to give this category a custom layout and this works without a problem.

I am wondering is there any easy way to apply this same layout to all subcategories of A (I don’t really want to have to create a custom template for every subcategory asthere is a lot)?

Related posts

2 comments

  1. If a is the category slug, then following code would work –

    add_action('template_include', 'wpse129481_template_include');
    function wpse129481_template_include($t)
    {
        // is category archive page
        if( is_category() )
        {
            // current queried category id from queried object
            $child_id = get_queried_object_id();
    
            // parent category object, getting it by slug.
            $parent_cat = get_term_by('slug', 'a', 'category');
    
            // current category object, can also be used get_queried_object()
            $child_cat = get_term($child_id, 'category');
    
            // important part here is the cat_is_ancestor_of() function.
            // it checks if first category is parent/grand parent of second
            if( isset($parent_cat->term_id) 
                && isset($child_cat->term_id)
                && $parent_cat->term_id != $child_cat->term_id
                && cat_is_ancestor_of( $parent_cat, $child_cat )
            )
            {
                locate_template( array('category-cat-a.php') );
            }
        }
        return $t;
    }
    
  2. I dont know if it’s the best way but one possibility that comes to mind is to hook the template_redirect function.

    If it where a custom post_type and I wanted children to a unique template I would do it like this. U need to tweek to work with taxonomys but the same principle apply.

    add_filter('template_redirect', 'page_template_override' );
    
    function page_template_override() {
        global $wp_query,$post;
    
      if(isset($wp_query->query_vars['posttype']) && $post->post_parent > 0){
                  include( get_template_directory() . '/template-name.php' );
               exit;
      }
    }
    

Comments are closed.