How to determine the depth of a term in a custom taxonomy?

I’m building a <select> dropdown to display a list of terms for a custom hierarchical taxonomy. How do I know the depth of each term? I’d like to add some indentation for child-terms (the more deeply they’re nested, the more indentation there should be).

However I’m not able to retrieve the depth level from get_terms(). How to get the depth level as an integer?

Related posts

Leave a Reply

2 comments

  1. <?php
    $args = array(
        'taxonomy' => 'category',
        'orderby' => 'name',
        'order' => 'ASC',
        'hierarchical'  => true,
        'hide_empty' => false,
    );
    $the_query = new WP_Term_Query($args);
    $categories = $the_query->get_terms();
    
    
    foreach($categories as $cat){
        $ancestors = get_ancestors( $cat->term_id, 'category' );
        $cat->ancestors = $ancestors; // array( 0 => 15, 1 => 45 ) - 3rd level term
        $cat->depth = count( $ancestors ) ;
    }
    ?>
    <select>
        <?php 
            foreach($categories as $cat){
                echo '<option value="'.$cat->term_id.'">'.str_repeat('&nbsp;&nbsp;&nbsp;',$cat->depth).$cat->name.'</option>';
            } 
        ?>
    </select>