term_is_ancestor_of()WP 3.4.0

Checks if the second term is a child of the first (all levels of nesting are checked). Conditional tag.

Will return true if the term specified in the first parameter is a parent in relation to the second. All levels of nesting will be checked.

Notes

  • The function will work if the second term is a child of the first;

  • The result true will be returned even if $term2 is nested in $term1 through several terms (multi-level nesting check);

  • The passed parameter must be either an int or an object. If a string is passed in the form of an int, the function will return false.
1 time — 0.000142 sec (fast) | 50000 times — 0.87 sec (very fast) | PHP 7.0.14, WP 4.7

No Hooks.

Returns

true|false.

  • true — when $term1 is a related term to term $term2.
  • false — when not related.

Usage

if( term_is_ancestor_of( $term1, $term2, $taxonomy ) ){
	// there is a dependency
}
$term1(int/object) (required)
ID or object that should be the parent term.
$term2(int/object) (required)
Child term.
$taxonomy(string) (required)
Name of the taxonomy to which the terms specified in $term1 and $term2 belong.

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.9.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 );
}