2013-09-24 25 views
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' 

回答

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)使用类别蛞蝓: 如果“单蔬菜”和“单果”是类蛞蝓,把下面的条件来加载基于类别蛞蝓在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 
} 
?> 
+0

谢谢!我会尝试这两种方法。我是否正确,它也适用于子类别? – kriskl

+0

是的,它也适用于子类别。 –

+0

嗨,它没有工作:(也许我做错了什么,但我更好地检查,是您的代码单个帖子模板?或自定义帖子类型模板?我现在只使用单一模板再次感谢您的支持 问题可能是我正在使用儿童主题(成因框架)? – kriskl