ccurtin
4/5/2017 - 6:47 PM

Loop through categories for a taxonomy term in WordPress

Loop through categories for a taxonomy term in WordPress!

<?php
/* Gets all sub-terms of a taxonomy-term and if no more exist, display posts for that term.  */
/* This doesn't need an action, should be added to the functions.php file */
function loop_through_cats($term_id){
  
    echo "<ul>";

      $args = array(
       'hierarchical' => 1,
       'hide_empty' => 0,
         'parent' => $term_id, // the "Articles" term ID.
         'taxonomy' => 'category'
     );

      $terms = get_categories($args);
      foreach ($terms as $term) {
        echo "<li>" . $term->name . "</li>";
        if (empty(get_term_children($term->term_id,'category')) ) { ?>

                <ul>
                <?php

                $args = array(
                  'post_type' => 'post',
                  'numberposts' => -1,
                  'tax_query' => array(
                    array(
                      'taxonomy' => 'category',
                      'field' => 'id',
                      'terms' => $term->term_id,
                    )
                  )
                );

                $myposts = get_posts( $args );
                foreach ( $myposts as $post ) :  ?>
                    <li>
                        <?php echo( $post->post_title ); ?>
                    </li>
                <?php endforeach; 
                wp_reset_postdata();?>

                </ul>


                <?php
        }
        loop_through_cats($term->term_id);
      }

  echo "</ul>";
}
?>`