Get a Term's Children in WordPress

Share

In WordPress, there are two ways to get a term's children from a hierarchical taxonomy using PHP. First, with get_term_children, which returns ALL children including from descendants as a single array, and second, with get_terms, by specifying the parent term ID.

Children and Descendants Method

Let's see the code to get the children and their descendants first. This is function is recursive and probably a bad idea considering how things are stored in SQL tables, but it's possible:

$parent_id = 42; // change this to the ID you want.
$taxonomy_name = 'category'; // change this to the taxonomy name you want.

$children_ids = get_term_children($parent_id, $taxonomy_name);
foreach($children_ids as $child_id) {
    $term = get_term($child_id, $taxonomy_name);
    // Do what you want here.
}

You may be wondering whether this loop is an N+1 query. It's probably not, because get_term_children calls _get_term_hierarchy, which is a private WordPress function, which calls get_terms, which updates a cache after fetching the data, so when we call get_term in the loop, that just takes the data from the cache instead of querying the database again.

In fact, it seems this get_term_children actually just loads ALL terms of a given taxonomy into memory as a single associative array by their parent ID and then does the recursive hierarchical tree filtering in the PHP side, rather than sending a new query for every layer of descendants.

We can also use get_terms for this passing a child_of argument1, but it will do pretty much the same thing we did above.

Only Direct Children Method

To get only the direct descendants of a term, we use get_terms passing a parent argument.

$parent_id = 42; // change this to the ID you want.
$taxonomy_name = 'category'; // change this to the taxonomy name you want.

$children = get_terms($taxonomy_name, array('parent' => $parent_id));
foreach($children as $term) {
    // Do what you want here.
}

References

  1. https://wordpress.stackexchange.com/questions/123912/non-recursive-get-term-children (accessed 2024-05-06). ↩︎

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *