最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - Apply custom category template to subcategories

programmeradmin2浏览0评论

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)?

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)?

Share Improve this question asked Jan 12, 2014 at 16:03 scrineymscrineym 1433 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 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;
}

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;
  }
}
发布评论

评论列表(0)

  1. 暂无评论