No, I’m not talking about actual children.  I’m talking about child categories, pages, or taxonomy terms.

All I wanted to do was check whether or not a given custom taxonomy term was a “child” of some other one.  I didn’t care how many levels deep it was in the hierarchy, I just wanted to know if it had a “parent” or not.  After a bit of Googling I couldn’t seem to find a nice, concise method of doing what I wanted, but with some experimentation this is what I cooked up in the lab:

1
2
3
4
function is_child($term,$taxonomy) {
    $check = get_ancestors($term->term_id,$taxonomy);
    if (!empty($check)) { return true;} else { return false;}
}

Line 1: function name, accepts two arguments: a term object and a taxonomy type.
Line 2: retrieves all the ancestors of the term object, puts them in array $check
Line 3: if the array has anything in it, returns true – this IS a child term.

Then in the loop where I want to exclude children I just run it as part of my check:

1
2
3
4
5
6
$taxonomy = get_terms('my_custom_taxonomy');
foreach ($taxonomy as $term) {
    if (!is_child($term,$taxonomy)) {
        // Exclude children from this
    }
};

If you actually needed term information or the array of ancestors returned, instead of just checking whether the term is a child or not, you could easily modify the function to return whatever you needed. You could also easily modify it to check whether a regular category or page is a child or not. The following (untested!) function should let you check if a category, page, or custom taxonomy is a child or not:

1
2
3
4
5
6
7
function is_child($what,$kind) {
    if ($kind == 'category') { $id = 'cat_id';
    } else if ( $kind == 'page') { $id = 'ID';
    } else { $id = 'term_id';}
    $check = get_ancestors($what->$id,$kind);
    if (!empty($check)) { return true; } else { return: false; }
}

Line 1: function name, takes an object as $what and a string for $kind.
Line 2: if $kind is a category set $id to cat_id
Line 3: otherwise if $kind is a page (actually uses $post) set $id to ID
Line 4: if it’s not a category or page it must be a custom taxonomy, set $id to term_id
Line 5: get ancestors of $what, if any and put in array $check
Line 6: if $check array is not empty return true, otherwise return false

You’d use it something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$categories = get_categories();
foreach ($categories as $cat) {
    if (!is_child($cat,'category')) {
        // exclude child categories from this
    }
};
$pages = get_pages();
foreach ($pages as $page) {
    if (!is_child($page,'page')) {
        // exclude child pages from this
    }
};
$taxonomy = get_terms('my_custom_taxonomy');
foreach ($taxonomy as $term) {
    if (!is_child($term,'my_custom_taxonomy')) {
        // exclude child terms of my taxonomy from this
    }
};