简体   繁体   中英

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 .

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 .

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:

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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM