Determine Term depth

I’m looking to be able to find the depth of a term within it’s hierarchical tree.

Produce
-- Vegetables
---- Carrot
---- Onion
---- Celery
-- Fruit
---- Apple
------ HoneyCrisp
----Orange

Produce is level 0 (or 1), Fruit is level 1, Apple is 2, HoneyCrisp is 3, etc.

Ideal usage is $depth = get_term_depth( $term_id );. Anyone have experience with this?

I essentially want a different rendering depending on depth on a term archive page.

1
1

Not trying to bump my rep, but I found my own answer. get_ancestors allows you to get the hierarchy of any item. Since terms can only have 1 parent, this is all we need: the number of items in this list equates to the term depth level, and even provides term ids.

Usage:

$ancestors = get_ancestors( $term_id, 'custom-taxonomy-slug' );
print_r( $ancestors ) ; // array( 0 => 15, 1 => 45 ) - 3rd level term

Leave a Comment