• Resolved NormanBird

    (@normanbird)


    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 .. etc

    fruits
    apples oranges mangoes …etc

    Im 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
    	?>
Viewing 1 replies (of 1 total)
  • Thread Starter NormanBird

    (@normanbird)

    I got it to work by replacing WP_Query() with query_posts() and that worked like a charm. Guess wp_query doesn’t play well with get_categories, that or I missed something about wp_query.

    so this is solved.

Viewing 1 replies (of 1 total)
  • The topic ‘Can I use wp_query inside a get_categories foreach’ is closed to new replies.