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

categories - Different template for subcategories

programmeradmin3浏览0评论

I would like to have a different template for categories and subcategories The categories template is set in categories.php is it somehow possible to load the subcategories template from subcategories.php or something like that?

I would like to have a different template for categories and subcategories The categories template is set in categories.php is it somehow possible to load the subcategories template from subcategories.php or something like that?

Share Improve this question asked Nov 25, 2016 at 10:55 TBHM adminTBHM admin 631 gold badge1 silver badge4 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 11

The template hierarchy has filters for all types of templates. Here we can use category_template, check if the current category has a parent, and load the subcategory.php file in that case:

function wpd_subcategory_template( $template ) {
    $cat = get_queried_object();
    if ( isset( $cat ) && $cat->category_parent ) {
        $template = locate_template( 'subcategory.php' );
    }

    return $template;
}
add_filter( 'category_template', 'wpd_subcategory_template' );

I have edited your code to add more functionality. For cases where someone would want to have a different template for each child category. For example if you have categories ordered like this:

  • continent
    • country
      • city

And you need a different template for city. First we look if city has a child, if not we call the template for city. The rest of code is to check if a category has a parent.

// Different template for subcategories
function wpd_subcategory_template( $template ) {
    $cat        = get_queried_object();
    $children   = get_terms( $cat->taxonomy, array(
        'parent'     => $cat->term_id,
        'hide_empty' => false
    ) );

    if( ! $children ) {
        $template = locate_template( 'category-country-city.php' );
    } elseif( 0 < $cat->category_parent ) {
        $template = locate_template( 'category-country.php' );
    }

    return $template;
}
add_filter( 'category_template', 'wpd_subcategory_template' );
发布评论

评论列表(0)

  1. 暂无评论