Others have asked how to only get parent terms, but I need to get the deepest term for the post of a specific taxonomy.
Is there a way I can only get terms where the number of children = 0?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityOthers have asked how to only get parent terms, but I need to get the deepest term for the post of a specific taxonomy.
Is there a way I can only get terms where the number of children = 0?
I have written this function some time ago, it may be a bit sloppy but it does it's job:
function get_low_level_term( $taxonomy ) {
$term = null;
if( is_single() ) {
global $post;
$terms = get_the_terms( $post->ID, $taxonomy );
if( count( $terms ) == 1 ) {
foreach( $terms as $t ) {
$term = $t;
}
}
else {
foreach( $terms as $t ) {
if( $t->parent ) {
$term = $t;
}
}
if( !$term ) {
$count = 0;
foreach( $terms as $t ) {
$term = $count == 0 ? $t : $term;
$count ++;
}
}
}
}
return $term;
}
There is another way to pass args to get terms. This worked for me.
$args = array(
"hide_empty" => false,
"taxonomy" => "category_taxonomy",
"childless" => true
);
$low_level_categories = get_terms($args);