这是我有 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'