wp_get_term_taxonomy_parent_id()
Returns the term's parent's term_ID.
Uses: get_term()
No Hooks.
Return
Int|false
. Parent term ID on success, false on failure.
Usage
wp_get_term_taxonomy_parent_id( $term_id, $taxonomy );
- $term_id(int) (required)
- Term ID.
- $taxonomy(string) (required)
- Taxonomy name.
Examples
#1 Get the ID of the parent element of the taxonomy
Suppose we have a taxonomy my_tax
which has a term with ID=5 and it has a child term with ID=10, then:
echo wp_get_term_taxonomy_parent_id( 10, 'my_tax' ); // outputs: 5
It is the same as:
Since the function gets the term with get_term() and checks its parent, the parent ID can also be obtained by this code:
$parent_term_id = get_term( 10, 'my_tax' )->parent ?? 0; echo $parent_term_id;
#2 Get the ID of the parent term of the top level
The code goes through all parents of the specified term until it reaches the top level. As a result we get the ID of the parent term of the top level:
$term_id = 5; // the ID of the child term while( $parent_id = wp_get_term_taxonomy_parent_id( $term_id, 'my_tax' ) ){ $term_id = $parent_id; } if( $term_id == 5 ){ echo 'The term has no parent elements.' } else { echo 'Top level parent ID: '. $term_id; }
Changelog
Since 3.1.0 | Introduced. |
wp_get_term_taxonomy_parent_id() wp get term taxonomy parent id code WP 6.7.1
function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) { $term = get_term( $term_id, $taxonomy ); if ( ! $term || is_wp_error( $term ) ) { return false; } return (int) $term->parent; }