Can I use wp_query inside a get_categories foreach
-
Im trying to loop through all the categories and also display the posts for each category as I go. so it would look like this:
animals
cats dogs horses .. etcfruits
apples oranges mangoes …etcIm using the code below. I was able to get the categories to list fine, then i added the wp_query loop stuff for the posts and it only displays the first category then nothing else. just white space. if i comment out the wp_query line, it loops and displays all the categories, but they all list the posts from only the first category.
SO im stuck. can i even use the wp_query inside a get_categories? if so is this correst? or do i need to cache or rewind or reset something? thanks
<?php $categories = get_categories($args); foreach($categories as $category) { echo '<p class="category-title">'. $category->name . ' ('.$category->count. ')</p><br />'; //start query of this categories posts $query = new WP_Query('cat='.$category->cat_ID); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); // Your loop code echo '<span class="post-names">'; $query->the_title(); echo '</span>'; endwhile; else : echo wpautop( 'Sorry, no info found' ); endif; //echo '<p> Description:'. $category->description . '</p>'; //echo '<p> Post Count: '. $category->count . '</p>'; } //foreach ?>
- The topic ‘Can I use wp_query inside a get_categories foreach’ is closed to new replies.