0

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?

2 Answers 2

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;
}
2

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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