0

这是我有 2 个(或更多)类别的场景,每个类别都有 5 个(或更多)子类别

类别 1 – 蔬菜(子类别:1)胡萝卜 2)番茄等 cat2 – 水果(子类别:1)苹果 2)橙子等

我为每个类别创建了单个模板:single-veg.php、single-fruit.php ..

那么,有谁知道在属于子类别的所有帖子上加载 single-veg.php 的正确函数应该是什么:“veg”、“carrot”等类别?

这是我采用的方法,但我认为必须有更好的方法..当然,如果您发现代码有任何问题......我是新手,任何帮助将不胜感激

/** Get Post Category and sub category */

function post_is_in_descendant_category( $cats, $_post = null )
{
    foreach ( (array) $cats as $cat ) {
        // get_term_children() accepts integer ID only
        $descendants = get_term_children( (int) $cat, 'category');
        if ( $descendants && in_category( $descendants, $_post ) )
            return true;
    }
    return false;
}

/** Conditional Templates for Single posts */

function template_change( $template ){

    if( is_single() && (post_is_in_descendant_category('12')) || in_category('12') ){
        $templates = array("single-veg.php");
    }
   elseif( is_single() && (post_is_in_descendant_category('17')) || in_category('17') ){
        $templates = array("single-fruit.php");
    } elseif( is_single() && in_category('articles') ){
        $templates = array("single-articles.php");
    }
    $template = locate_template( $templates );
    return $template;
}

add_filter( 'single_template', 'template_change' ); //'template_include'/'single_template'
4

1 回答 1

0

1)使用帖子格式:

首先,您可以为这两个类别创建不同的帖子格式(将以下内容放在functions.php中):

add_theme_support( 'post-formats', array( 'single-veg', 'single-fruit' ) );

现在您可以使用帖子格式。您可以在管理区域为每个帖子选择一个帖子格式,然后在 single.php 中调用以下内容来为每种格式加载不同的文件。

<?php
    if ( has_post_format( 'single-veg' )) {
        get_template_part( 'content', 'single-veg' ); // includes content-single-veg.php
    } else if ( has_post_format( 'single-fruit' )) {
        get_template_part( 'content', 'single-fruit' ); // includes content-single-fruit.php
    }
?>

2)使用分类 slug: 如果 'single-veg' 和 'single-fruit' 是分类 slug,设置以下条件以根据分类 slug 在 single.php 中加载 2 个不同的文件。

<?php
if(in_category('single-veg')) {
  get_template_part( 'content', 'single-veg' ); // includes content-single-veg.php
}
elseif(in_category('single-fruit')) {
  get_template_part( 'content', 'single-fruit' ); // includes content-single-fruit.php
}
?>
于 2013-09-24T10:20:53.660 回答