get_term_children()WP 2.3.0

Gets all child elements of the specified taxonomy element (categories) as an array.

This function will combine all levels of child sections into one array, i.e., if we specified a taxonomy element 10 which has a child element 15, and it, in turn, has a section 20, then the function will gather data about taxonomy elements 15 and 20 into a single array.

The function is logically used only for tree-type taxonomies.

This is a recursive function (calls itself) that only collects data, while the term IDs are obtained from _get_term_hierarchy().

1 time — 0.000048 sec (very fast) | 50000 times — 0.75 sec (very fast) | PHP 7.0.5, WP 4.5.2

No Hooks.

Returns

Array|WP_Error. An array of IDs of child elements of the taxonomy or a WP_Error object in case of an error.

Usage

$terms = get_term_children( $term, $taxonomy );
$term(number) (required)
ID of the term whose all child sections need to be retrieved.
$taxonomy(string) (required)
The name of the taxonomy with which the function will work.

Examples

0

#1 Usage example

Let's display the names of the child sections of taxonomy element 10, as links to the corresponding pages of the archives:

$term_id     = 10; // get_queried_object()->term_id; - current category ID (dynamic)
$tax_name    = 'products';
$term_childs = get_term_children( $term_id, $tax_name );

echo '<ul>';
foreach ( $term_child as $child ) {

	$term = get_term_by( 'id', $child, $tax_name );

	echo '<li><a href="' . get_term_link( $term ) . '">' . esc_html( $term->name ) . '</a></li>';
}

echo '</ul>';

As a result of executing this code, we get something like this on the screen:

<ul> 
	<li><a href="http://example.com">Term Name 1</a></li>
	<li><a href="http://example.com">Term Name 2</a></li>
</ul>

Changelog

Since 2.3.0 Introduced.

get_term_children() code WP 6.8.1

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 ) {
			continue;
		}

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

	return $children;
}