Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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;
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.