term_is_ancestor_of

Check if a term is an ancestor of another term.

Description

term_is_ancestor_of( (int|object) $term1, (int|object) $term2, (string) $taxonomy ); 

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

Parameters (3)

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

Usage

  1. if ( !function_exists( 'term_is_ancestor_of' ) ) { 
  2. require_once ABSPATH . WPINC . '/taxonomy.php'; 
  3.  
  4. // ID or object to check if this is the parent term. 
  5. $term1 = null; 
  6.  
  7. // The child term. 
  8. $term2 = null; 
  9.  
  10. // Taxonomy name that $term1 and `$term2` belong to. 
  11. $taxonomy = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = term_is_ancestor_of($term1, $term2, $taxonomy); 
  15.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/taxonomy.php  
  1. function term_is_ancestor_of( $term1, $term2, $taxonomy ) { 
  2. if ( ! isset( $term1->term_id ) ) 
  3. $term1 = get_term( $term1, $taxonomy ); 
  4. if ( ! isset( $term2->parent ) ) 
  5. $term2 = get_term( $term2, $taxonomy ); 
  6.  
  7. if ( empty( $term1->term_id ) || empty( $term2->parent ) ) 
  8. return false; 
  9. if ( $term2->parent == $term1->term_id ) 
  10. return true; 
  11.  
  12. return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy );