get_term_children( int $term_id, string $taxonomy ): array|WP_Error

Merges all term children into a single array of their IDs.


This recursive function will merge all of the children of $term into the same array of term IDs. Only useful for taxonomies which are hierarchical.

Will return an empty array if $term does not exist in $taxonomy.


ID of term to get children.
Taxonomy name.


array|WP_Error List of term IDs. WP_Error returned if $taxonomy does not exist.


function get_term_children( $term_id, $taxonomy ) {
	if ( ! taxonomy_exists( $taxonomy ) ) {
		return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );

	$term_id = (int) $term_id;

	$terms = _get_term_hierarchy( $taxonomy );

	if ( ! isset( $terms[ $term_id ] ) ) {
		return array();

	$children = $terms[ $term_id ];

	foreach ( (array) $terms[ $term_id ] as $child ) {
		if ( $term_id === $child ) {

		if ( isset( $terms[ $child ] ) ) {
			$children = array_merge( $children, get_term_children( $child, $taxonomy ) );

	return $children;



User Contributed Notes

  1. Skip to note 4 content

    A Basic Example
    Used to get an array of children taxonomies and write them out with 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>';

    This would return something like.

    <li><a href="link_to_term_page">Term 1</a></li>
    <li><a href="link_to_term_page">Term 2</a></li>
  2. Skip to note 5 content

    Categories and Tags are the two pre-defined Taxonomies. 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’.

You must log in before being able to contribute a note or feedback.