get taxonomy terms for parent and child

I have a function set up that prints the taxonomy term name and slug for every products-category taxonomy term present. This works great, but it’s just displaying them alphabetically like so (regardless of if they are a parent / child taxonomy term):

Parent Category 2
Parent Category 1
Child Category 3
Parent Category 3
Child Category 2
Child Category 1 
etc...

Whereas I’m after a structure more like this:

—Parent Category 1
Child Category 1
Child Category 2
Child Category 3

—Parent Category 2
Child Category 1
Child Category 2
Child Category 3

—Parent Category 3
Child Category 1
Child Category 2
Child Category 3

So the children terms of each taxonomy term sit underneath, so you know what parent they belong to. My markup is as follows:

<?php
$args = array(
    'hide_empty' => false
);  
 $terms = get_terms("products-category");
 if ( !empty( $terms ) && !is_wp_error( $terms ) ){
     foreach ( $terms as $term ) { ?>
      <option value=".<?php echo $term->slug; ?>" data-hook="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>
    <?php }
 } ?>   

Any suggestions on how to achieve this would be greatly appreciated!

2 Answers
2

You should have two foreach loops. One for getting parent taxonomy terms, and second for getting child taxonomy terms.

In the second foreach you need to specify the parent taxonomy term ID which is $parent_term->term_id from the first foreach loop.

foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => 0 ) ) as $parent_term ) {
  // display top level term name
  echo $parent_term->name . '<br>';

  foreach( get_terms( 'products-category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term ) {
    // display name of all childs of the parent term
    echo $child_term->name . '<br>';
  }

}

Leave a Comment