Here’s a quick helper function to find the top level ancestor of a given term. If you like to organize your categories in nested fashion, this function will find the very top level parent no matter how deep down the term your working with is nested.
/** * Get the top level parent of a given term. * @param WP_Term|int The term who's ancestors we'll be tracing. * @param string Name of taxonomy to search. Required only if $term is an ID instead of a WP_Term object. * @return WP_Term|bool The top level parent of $term. If $term has no parent, return false. */ function get_term_progenitor( $term, $tax = 'category' ) { if ( is_int( $term ) ) { $term = get_term_by( 'id', $term, $tax ); } if ( 0 == $term->parent || ! $term instanceof WP_Term ) { return false; } while ( $term instanceof WP_Term && 0 != $term->parent ) { $term = get_term_by( 'id', $term->parent, $term->taxonomy ); } return $term; }
To use it feed in a term object or a term id and taxonomy combo to get the original ancestor of your term. If your term has no parent, it will return false. This is helpful if you need to apply a class to a whole tree of terms, for example. If your
It’s worth noting that this function will call get_term_by()
multiple times, and it is known to create slower database queries. If you have nested your terms more than a few levels it may be worth storing the results of this function in a persistent object cache to speed up performance.
The post Find the top level parent term appeared first on Scott Nelle.