[英]How to create custom page for category and single page for specifed category with its children in wordpress
I want to create custom page for category and single page for specifed category with its children . 我想为类别创建自定义页面,为指定类别及其子级创建单个页面。
First , to create custom single page i've used this code 首先 ,要创建自定义单个页面,我使用了以下代码
if (in_category('blog')){
include (TEMPLATEPATH . '/single-blog.php');
}elseif(in_category('projects')){
include (TEMPLATEPATH . '/single-projects.php');
}
else{
include (TEMPLATEPATH . '/single-default.php');
}
and it work fine just for specifed ctegory in the code and doesn't support the children of category. 它仅适用于代码中指定的分类,并且不支持类别的子级。
fo example : i would like to use single-blog.php
for single page of posts that its category is blog
or children of blog
. 例如:我想对类别为blog
或blog
children of blog
类的帖子的单个页面使用single-blog.php
。
Second , for category page i want to do the same things that i've explained above for list of category's posts . 其次 ,对于类别页面,我想做与上文针对类别帖子列表所述的相同的操作。
fo example : i would like to show the list of posts that is related to blog category or its children in category-blog.php
. 例如:我想在category-blog.php
显示与博客类别或其子category-blog.php
相关的帖子列表。
how can i do it. 我该怎么做。
For the first part of your question, you're probably looking for cat_is_ancestor_of
, so you'd write something like this: 对于问题的第一部分,您可能正在寻找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
}
For the second part, I understand that you want to do the same thing but for an archive page. 对于第二部分,我了解到您想要做同样的事情,但是要存档页面。 In that case, it's a bit simpler as you won't have an array of categories: 在这种情况下,这会更简单,因为您将没有类别数组:
$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
}
Let me know if this works for you, 让我知道这是否适合您,
EDIT - Here's an alternative option (not tested) that doesn't use --at least directly-- a foreach
loop. 编辑 -下面是一个备选方案(未测试)不使用--at至少directly--一foreach
循环。 Not sure if it's higher performance though. 虽然不确定它是否具有更高的性能。
$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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.