0

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

3

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
}
  • 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='.$categoryid); 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
0

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);
}
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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