term_is_ancestor_of()WP 3.4.0

Check if a term is an ancestor of another term.

You can use either an ID or the term object for both parameters.

1 time — 0.000142 sec (fast) | 50000 times — 0.87 sec (very fast) | PHP 7.0.14, WP 4.7

No Hooks.

Return

true|false. Whether $term2 is a child of $term1.

Usage

term_is_ancestor_of( $term1, $term2, $taxonomy );
$term1(int|object) (required)
ID or object to check if this is the parent term.
$term2(int|object) (required)
The child term.
$taxonomy(string) (required)
Taxonomy name that $term1 and $term2 belong to.

Examples

0

#1 Checking taxonomy element relatedness

Suppose we have a custom tree-like taxonomy my_tax and the term with ID 5 is a child of the term with ID 1. Then this condition is valid:

if( term_is_ancestor_of( 1, 5, 'my_tax') ){

	echo 'Term 4 is a child of term 1;
}
0

#2 Content for the entire terms branch

This example is useful when you want to output specific content for an entire branch of terms. That is when you want to output content for any child terms to the specified term and for the specified term (ID=4).

The code below checks if the term Music (ID 4) from the sound taxonomy is used, and if it is this term or any of its children, it outputs the menu, using the function wp_nav_menu():

<?php 

// $term is the current term being viewed 
// You can get it this way if you need to:
// $term = get_term_by( 'slug', get_query_var('term'), 'sound');
if ( term_is_ancestor_of( 4, $term, 'sound') || is_term( 4, 'sound') ) {
	?>
	<div id="music_subnav_menu" class="subnav_menu">
		<?php wp_nav_menu( array('menu' => 'Music' )); ?>
	</div>
	<?php
}
?>

Changelog

Since 3.4.0 Introduced.

term_is_ancestor_of() code WP 6.1.1

function term_is_ancestor_of( $term1, $term2, $taxonomy ) {
	if ( ! isset( $term1->term_id ) ) {
		$term1 = get_term( $term1, $taxonomy );
	}
	if ( ! isset( $term2->parent ) ) {
		$term2 = get_term( $term2, $taxonomy );
	}

	if ( empty( $term1->term_id ) || empty( $term2->parent ) ) {
		return false;
	}
	if ( $term2->parent === $term1->term_id ) {
		return true;
	}

	return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );
}