custom taxonomy – Create a hierarchical list of posts that’s grouped and nested by category

Question

I’m trying to show a list of book recommendations, grouped and sorted by category. The problem is some book recommendations belong only to a top-level category and some belong to sub-categories.

I’d like to display the list like this:

Book Sub Category 1

Book Sub Category 2

I’ve gotten the list to display all parent level categories, and books belonging to a sub-category but can’t figure out how to create a condition for book recommendations that belong just to a parent category.

Here’s my code:

        $terms_array = array( 
          'taxonomy' => 'book_category',
          'parent'  => 0,
        );
        $book_category_parents = get_terms($terms_array);
        foreach($book_category_parents as $book_category_parent): ?>

        <h1><?php echo $book_category_parent->name; ?></h1>

        <?php 
            $subterms_array = array( 
              'taxonomy' => 'book_category',
              'parent'  => $book_category_parent->term_id,
            );
            $book_category_children = get_terms($subterms_array);
            foreach($book_category_children as $book_category_child): ?>

            <h2 class="dark-gray"><?php echo $book_category_child->name; ?></h2>

            <?php
                $post_args = array(
                      'posts_per_page' => -1,
                      'post_type' => 'book',
                      'tax_query' => array(
                          array(
                              'taxonomy' => 'book_category',
                              'field' => 'term_id',
                              'terms' => $book_category_child->term_id,
                          )
                      )
                );
                $myposts = get_posts($post_args); ?>
                
                <ul>
                    <?php foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
                        <li>
                            <a href="#"><?php the_title(); ?></a>
                        </li>
                    <?php endforeach; ?>
                </ul>
        <?php endforeach; ?> 
    <?php endforeach; ?>

This doesn’t display anything for books with only a parent level category.

0
Robert 2 months 2023-01-31T21:14:56-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse