0

I have a custom taxonomy, which is structured like

Cars
--Ford
--VW
Trucks
--Ford
--Dodge

And then I have posts in this post type such as "Beetle" and "Jetta" assigned to the "VW" subcategory and "Ram" assigned to the "Dodge" subcategory

I am able to loop and display the vehicle types and the brands under it, but I am having a problem getting the args for my loop correct to display the actual vehicles (for example, show "Beetle" and "Jetta" under VW).

If I hard-code the brand, it works but I need the correct variable in my foreach loop. What I have now just displays the list of types, brands, but then all vehicles under each brand (e.g. all 3 cars mentioned above are shown under all brands).

  <?php /*Template Name: Category test */ ?>

  <?php
     $wcatTerms = get_terms( array(
           'taxonomy' => 'api_category',
           'hide_empty' => false,
     ) );

     foreach($wcatTerms as $wcatTerm) : 
  ?>

  <ul>
     <li>
        <?php echo $wcatTerm->name; ?>
        <ul class="megaSubCat">
           <?php
              $wsubargs = array(
                 'hierarchical' => 1,
                 'show_option_none' => '',
                 'hide_empty' => 0,
                 'parent' => $wcatTerm->term_id,
                 'taxonomy' => 'api_category'
              );
              $wsubcats = get_categories($wsubargs);
              foreach ($wsubcats as $wsc):
              ?>

           <li><?php echo $wsc->name;?><!-- up to this point, works -->

              <?php  
                 $args = array(
                    'post_type' => 'apis', 
                    'tax_query' => array( 
                       'relation' => 'AND',
                       array(
                          'taxonomy' => 'api_category', 
                          'field' => 'term_id', 
                          'terms' => $wsc->name
                       ) 
                    ), 
                    'orderby' => 'title', 
                    'order' => 'ASC', 
                    'posts_per_page' => -1 
                 ); 
              ?>


              <?php $loop = new WP_Query( $args ); ?>

              <ul>
                 <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
                    <li><?php the_title();?></li><!-- displays every vehicle from all makes and classes -->
                 <?php endwhile; ?>
              </ul>         

           </li>

           <?php endforeach; ?>  

        </ul>
     </li>
  </ul>
  <?php endforeach; ?>
  • 1
    you are mixing up your tax_query. you ask for looking at the term_id and than you hand over the term name.. 'terms' => $wsc->term_id should fix it. – honk31 Oct 10 '18 at 8:32

Your Answer

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

Browse other questions tagged or ask your own question.