开发者

Wordpress: is child of category function

I I am looking for a function that merely returns true or false. The function would check if the category archive being queried is a child of a particular parent category. The function would look something like this (similar to the is_category() function):

if(is_child_of_category('3')){ //do something }
if(is_child_of_category('4')){ //do something else }
if(is_child_of_category('5')){ //do something entirely different }

I have looked through the documentation and the forums but have not found any solutions, any ideas if this has been done or how one would go about it?

///////////// addendum ////////////

Here is the working code that I wrote with help from Gavin:

Thanks Gavin

first a function for the functions.php file to get the category id:

function getCurrentCatID(){
global $wp_query;
if(is_category() || is_single()){
$cat_ID = get_query_var('cat');
}
return $cat_ID;
}

Next use cat_is_ancestor_of

$post = $wp_query->post;
$id = getCurrentCatID();

if ( cat_is_ancesto开发者_开发知识库r_of(3, $id) { include(TEMPLATEPATH . '/unique.php'); }


cat_is_ancestor_of

This will return true still, however, if the category is a grandchild of the specified category.


I need something similar yesterday, so I wrote this function which hands me back an array with all the child categories + the parent-category (which might be useful if you want to, let's say, hide the comment form on all FAQ-cat posts and childs thereof, but show it on others).

Pass $catname as a var and get an array back, which you can use as an argument in e.g. in_category() function.

// Get List of Child Categories
function get_child_cats( $catname ) {
    $parentcat = get_cat_ID( '$catname' );
    $subcat = get_categories( array('child_of' => $parentcat ) );
    $cat_array = array();
    array_push($cat_array, $parentcat); // add the parent cat to the array
    foreach ($subcat as $sc) {
        array_push($cat_array, $sc->cat_ID);
    }
    return $cat_array;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜