wp_get_term_taxonomy_parent_id()
Gets the ID of the parent element of the taxonomy (term) for the specified one.
If you have a ready term object, then the parent ID is located in the parent parameter: $term->parent
Uses: get_term()
No Hooks.
Returns
Int|false. Integer/boolean: ID of the parent term or false.
Usage
wp_get_term_taxonomy_parent_id( $term_id, $taxonomy );
- $term_id(integer/WP_Term) (required)
- ID or term object whose parent ID needs to be obtained.
- $taxonomy(string) (required)
- Name of the taxonomy in which the element specified in $term_id is located.
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 7.0
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;
}