WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/ get term hierarchy

_get_term_hierarchy ( string $taxonomy )

Retrieves children of taxonomy as Term IDs.

Returns: (array) Empty if $taxonomy isn't hierarchical or returns children as Term IDs.

Eg.

   <?php
   /** The taxonomy we want to parse */
   $taxonomy = "category";
   /** Get all taxonomy terms */
   $terms = get_terms($taxonomy, array(
           "orderby"    => "count",
           "hide_empty" => false
       )
   );
   /** Get terms that have children */
   $hierarchy = _get_term_hierarchy($taxonomy);
       /** Loop through every term */
       foreach($terms as $term) {
       //Skip term if it has children
       if($term->parent) {
         continue;
       } 
         echo $term->name;    
       /** If the term has children... */
         if($hierarchy[$term->term_id]) {
       /** display them */
       foreach($hierarchy[$term->term_id] as $child) {
       /** Get the term object by its ID */
       $child = get_term($child, "category_list");
            echo '--'.$child->name;
           }
        }
     }
 ?>