Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

question is simple (i don't know is aswer too ;)
I just want to check that, does a category has child (or is ancestor) from its cat-id with a function.
Eg.
function check_category ($catid){
............
...//true if is ancestor, false if not
return $result;
}

Note: I can only pass cat-id parameter for function because i need to use it in functions.php
Thanks in advance...

share|improve this question

2 Answers 2

up vote 2 down vote accepted

You can do something like this:

function category_has_parent($catid){
    $category = get_category($catid);
    if ($category->category_parent > 0){
        return true;
    }
    return false;
}

and use it like this:

if (category_has_parent('22')){
   //true there is a parent category
}else{
   //false this category has no parent
}

Update:

to check the other way around (if a category has children) you can use get_categories

$children = get_categories(array('child_of' => id,'hide_empty' => 0));
if (count($children) > 1){
    //has childern
}else{
    //no children
}
share|improve this answer
    
First snippet can be probably streamlined to return $category->category_parent. –  Rarst Mar 6 '11 at 19:58
    
@Bainternet, I'am sory but i asked question incorrect. I want to learn that is this category ($catid) endmost? I mean, if a category has no child then it is endmost.. Thanks in advance... –  Alper Mar 6 '11 at 21:06
    
So you need the opposite of that, instead of checking if it has a parent you want to check if it has child categories? –  Bainternet Mar 6 '11 at 21:33
    
@Bainternet, yes and i've sold my problem with: $catlist = wp_list_categories('echo=0&orderby=id&hide_empty=0&title_li=&child_of='.$categor‌​yid); if (($catlist)!='<li>No categories</li>') –  Alper Mar 7 '11 at 0:42
    
@Alper , check the answer again, I've added a much nicer way to do it. –  Bainternet Mar 7 '11 at 1:01

Have a look at the Codex: http://codex.wordpress.org/Function_Reference/get_category_parents

// returns true or false    
function check_category( $cat_id ){
    $parent = '';
    $parent = get_category_parents( $cat_id );
    return empty($parent);
}
share|improve this answer
    
I don't think this will work, by mechanics get_category_parents() its output will always have at least category itself. –  Rarst Mar 6 '11 at 20:00
    
I'am sory but i asked question incorrect. I want to learn that is this category ($catid) endmost? I mean, if a category has no child then it is endmost.. Thanks in advance... –  Alper Mar 6 '11 at 21:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.