Using WordPress ‘get_term_children()’ PHP function

The get_term_children() WordPress PHP function merges all term children into a single array of their IDs.

Usage

get_term_children($term_id, $taxonomy_name)

Input:
$term_id: 10, $taxonomy_name: ‘products’

Output:
Array of children term IDs

Parameters

  • $term_id (int): Required ID of term to get children.
  • $taxonomy_name (string): Required taxonomy name.

More information

See WordPress Developer Resources: get_term_children

Note

Categories and Tags are the two pre-defined taxonomies in WordPress. The Taxonomy Name, the second required parameter $taxonomy, is ‘category’ for Categories and ‘post_tag’ for Tags. If replacing the deprecated function get_category_children(), which returns a string, note that get_term_children() returns an array of category IDs if the second parameter $taxonomy is ‘category’.

Examples

Displaying child terms in an unordered list

This example gets an array of children taxonomies and displays them as links in an unordered list.

$term_id = 10;
$taxonomy_name = 'products';
$termchildren = get_term_children($term_id, $taxonomy_name);

echo '<ul>';
foreach ($termchildren as $child) {
  $term = get_term_by('id', $child, $taxonomy_name);
  echo '<li><a href="' . get_term_link($child, $taxonomy_name) . '">' . $term->name . '</a></li>';
}
echo '</ul>';