1

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?

1

You can use wp_dropdown_categories():

Display or retrieve the HTML dropdown list of categories.

$args = array(
    'show_count'   => 1,
    'hierarchical' => 1,
    'taxonomy'     => 'my_taxonomy',
);

wp_dropdown_categories( $args );
  • Thanks, but I have a problem with this solution... what if I want to insert some onchange javascript in the <select> and put the term link in the <option> value? In this way the user would get redirected to the term archive by selecting the corresponding item in the list. wp_dropdown_categories() only outputs a plain list if I'm not mistaken. – unfulvio Jan 15 '13 at 13:38
  • uh... just thought of it, maybe I can create a custom walker for wp_dropdown_categories... – unfulvio Jan 15 '13 at 13:41
  • or even more practically, I could do this with javascript, just found a valid example in codex codex.wordpress.org/Function_Reference/wp_dropdown_categories - apparently wp_dropdown_categories doesn't accept a custom walker in the args – unfulvio Jan 15 '13 at 13:55
  • But basically, your question has been answered? It would be nice if you could do the job with javascript. – Mike Madern Jan 15 '13 at 13:59
  • there is some method descriped in codex.wordpress.org/Function_Reference/wp_dropdown_categories but URLs created with those methods will return 404 if one uses pretty permalinks, URL rewrites seem not to correct the problem (or maybe they work with blog posts only? in my case is a custom taxonomy) – unfulvio Jan 15 '13 at 17:06
0
<?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>
  • Thank you for your post, but would you please edit it and explain how this solves the OP's question. – Dave Romsey Jul 8 '17 at 20:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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