Make Wordpress subcategories use Category Template

2020-02-01 02:37发布

I've got a category template: category-projects.php

This category has subcategories, but they're refering to the template category.php for instructions instead of the parent category. How do I make subcategories refer to parent category templates in the cascading order of template references?

*Note, I'm talking about category level urls, not posts.

3条回答
戒情不戒烟
2楼-- · 2020-02-01 02:43

One way to do this is to hook into the template_redirect action in your functions.php file:

function myTemplateSelect() {
    if (is_category() && !is_feed()) {
        if (is_category(get_cat_id('projects')) || cat_is_ancestor_of(get_cat_id('projects'), get_query_var('cat'))) {
            load_template(TEMPLATEPATH . '/category-projects.php');
            exit;
        }
    }
}

add_action('template_redirect', 'myTemplateSelect');
查看更多
爷、活的狠高调
3楼-- · 2020-02-01 02:44

Richard's answer does work but it will heavily interfere with other plugins.

I found a better alternative using add_filter & template_include as the example below

add_filter( 'template_include', 'my_callback' );

function my_callback( $original_template ) {
    if ( some_condition() ) {
        return SOME_PATH . '/some-custom-file.php';
    } else {
        return $original_template;
    }
}

Credit to https://markjaquith.wordpress.com/2014/02/19/template_redirect-is-not-for-loading-templates/

查看更多
唯我独甜
4楼-- · 2020-02-01 03:03

As far i know; according to wp template hierarchy, category-samplecat.php is only applies to a category with slug name "samplecat". So it's not possible to do it in this way.

But in the category.php file (that applies to every category which hasn't a special template file) you can make a conditional check if current category is a child of "project" (using this method in my answer to your other question) and if so you can apply same structure of category-projects.php to it or include category-projects.php.

查看更多
登录 后发表回答