WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Can I use wp_query inside a get_categories foreach (2 posts)

  1. NormanBird
    Member
    Posted 2 years ago #

    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
    	?>
  2. NormanBird
    Member
    Posted 2 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic