2016-08-13 133 views
0

我想创建自定义页面的类别和单页面的指定类别与其子。如何创建自定义页面的类别和单页面的指定类别与其子在wordpress

首先,创建自定义的单页我用这个代码

if (in_category('blog')){ 
include (TEMPLATEPATH . '/single-blog.php'); 
}elseif(in_category('projects')){ 
    include (TEMPLATEPATH . '/single-projects.php'); 
} 
else{ 
    include (TEMPLATEPATH . '/single-default.php'); 
} 

,并在代码中很好地工作只是为了specifed ctegory,不支持类的孩子。

fo例如:我想使用single-blog.php单页的文章,其类别是blogchildren of blog

第二,对于类别页我想做同样的事情,我已经解释了上面的类别的职位列表。

fo例如:我想在category-blog.php中显示与博客类别或其子项相关的帖子列表。

我该怎么做。

回答

1

对于你的问题的第一部分,你可能寻找cat_is_ancestor_of,所以你写的东西是这样的:

function is_ancestor_of($ancestor_category) { 
    $categories = get_the_category(); // array of current post categories 
    foreach ($categories as $category) { 
     if (cat_is_ancestor_of($ancestor_category, $category)) return true; 
    } 
    return false; 
} 

$ancestor_category = get_category_by_slug('blog'); 
if (in_category('blog') || is_ancestor_of($ancestor_category)) { 
    // include 
} 

对于第二一部分,我知道你是想做同样的事情,但为一个档案页面。在这种情况下,你不会有类别的数组这是一个有点简单:

$archive_category = get_category(get_query_var('cat')); // current archive category 
$ancestor_category = get_category_by_slug('blog'); 
if (is_category('blog') || cat_is_ancestor_of($ancestor_category, $archive_category) { 
    // include 
} 

让我知道这对你的作品,

编辑 - 这里是另一种选择(未测试),不直接使用 - 至少直接使用foreach循环。不知道它是否具有更高的性能。

$ancestor_category = get_category_by_slug('blog'); 
$children_categories = get_categories(array ('parent' => $ancestor_category->cat_ID)); // use 'child_of' instead of 'parent' to get all descendants, not only children 

$categories = get_the_category(); // array of current post categories 

if (in_category('blog') || ! empty(array_intersect($categories, $children_categories)) { 
    // include 
} 
+0

谢谢,波尔。它的作品像一个魅力,但我希望有另一种不使用foreach的方式,因为它有点低性能 – Ali

+0

@Hamed你可能想要测试我的编辑,看看它是否表现更好,我不知道 –

+0

我'经过测试,但它不起作用 – Ali

相关问题