让所有WordPress分类使用它们的父分类模板

15

我想要改变默认的模板层次结构行为,并强制所有没有自己的类别模板文件的子分类级别页面参考其父级分类模板文件。在我的另一篇帖子中,Richard M.给出了一个很好的答案,解决了单个子类别的问题。有人知道如何抽象它吗?

function myTemplateSelect()
{
    if (is_category()) {
        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个回答

24
/**
 * Iterate up current category hierarchy until a template is found.
 * 
 * @link https://dev59.com/_nA75IYBdhLWcg3wxb_V#3120150
 */ 
function so_3119961_load_cat_parent_template( $template ) {
    if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
        $term = get_queried_object();

        while ( $term->parent ) {
            $term = get_category( $term->parent );

            if ( ! $term || is_wp_error( $term ) )
                break; // No valid parent

            if ( $_template = locate_template( "category-{$term->slug}.php" ) ) {
                // Found ya! Let's override $template and get outta here
                $template = $_template;
                break;
            }
        }
    }

    return $template;
}

add_filter( 'category_template', 'so_3119961_load_cat_parent_template' );

该代码循环向上查找父级模板,直到找到最近的一个。


我刚试了一下,但无法使其工作。您能否再检查一下? - Matrym
2
TEMPLATEPATH 而不是 TEMPLATE_PATH - Richard M
5
在使用子主题的functions.php中,将TEMPLATEPATH替换为get_stylesheet_directory() - mhawksey
谢谢,这很有帮助! - foxybagga

4

我想知道如何对分层分类进行相同的操作。TheDeadMedic的回答在这种情况下似乎也有效,只需要进行一些微调:

function load_tax_parent_template() {
    global $wp_query;

    if (!$wp_query->is_tax)
        return true; // saves a bit of nesting

    // get current category object
    $tax = $wp_query->get_queried_object();

    // trace back the parent hierarchy and locate a template
    while ($tax && !is_wp_error($tax)) {
        $template = STYLESHEETPATH . "/taxonomy-{$tax->slug}.php";

        if (file_exists($template)) {
            load_template($template);
            exit;
        }

        $tax = $tax->parent ? get_term($tax->parent, $tax->taxonomy) : false;
    }
}
add_action('template_redirect', 'load_tax_parent_template');

2
TEMPLATEPATH 变量可能无法用于子主题 - 它会在父主题文件夹中查找。请改用 STYLESHEETPATH。例如:
$template = STYLESHEETPATH . "/category-{$cat->slug}.php";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接