【问题标题】:How to apply parent category template for child category in wordpress?如何在wordpress中为子类别应用父类别模板?
【发布时间】:2019-10-10 18:51:54
【问题描述】:

我尝试为指定类别构建自定义模板,我的类别是新闻,我创建了一个名称为 "category-news.php" 的模板,在 "新闻" 类别中我有一些子类别,现在我想应用父类别子类别的类别模板,我在下面测试了这段代码,但它不起作用。

function wp_category_template() {
$category = get_queried_object();
$parent_id = $category->category_parent;
$templates = array();
if ( $parent_id == 0 ) {
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
$templates[] = 'category.php';
} else {
$parent = get_category( $parent_id );
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
$templates[] = "category-{$parent->slug}.php";
$templates[] = "category-{$parent->term_id}.php";
$templates[] = 'category.php';
}
return locate_template( $templates );
}
add_filter( 'category_template', 'wp_category_template' );

【问题讨论】:

    标签: wordpress categories


    【解决方案1】:

    也许您可以尝试以下方法:

    创建名为 template-news.php 的新文件并将内容从 category-news.php 移动到该文件。

    然后是category.php,你可以检查category是否是news或者这个category是否有news的父类然后加载template-news.php文件。

    在 category.php 中添加:

    $category = get_queried_object();
    $parent = false;
    if ( $category->parent ) {
        $parent = get_term_by('id', $category->parent, 'category');
    }
    if ( is_category('news') || ( $parent && $parent->slug === 'news' ) {
        include_once get_template_directory() . '/template-news.php';
    }
    

    注意:我没有测试过这个,但是概念很清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多