Check is category parent or not from its ID

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…

Related posts

Leave a Reply

2 comments

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