0
这里是场景 我有2(或更多)的类别和各自具有5(或更多)子类别类别和子类别控制哪个单独发布模板应该加载?
CAT1 - 蔬菜(SUBCAT:1)胡萝卜2)番茄等 CAT2 - 果(SUBCAT:1)苹果2)橙等
我已经为每个类别单模板创建: 单veg.php,单fruit.php ..
因此,没有人知道什么是应该是装载单一正确的函数-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'
谢谢!我会尝试这两种方法。我是否正确,它也适用于子类别? – kriskl
是的,它也适用于子类别。 –
嗨,它没有工作:(也许我做错了什么,但我更好地检查,是您的代码单个帖子模板?或自定义帖子类型模板?我现在只使用单一模板再次感谢您的支持 问题可能是我正在使用儿童主题(成因框架)? – kriskl