Support » Fixing WordPress » Can I use wp_query inside a get_categories foreach

  • Resolved 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:

    cats dogs horses .. etc

    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

    	$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">';
    							echo '</span>';
    						else :
    						echo wpautop( 'Sorry, no info found' );
    		//echo '<p> Description:'. $category->description . '</p>';
    		//echo '<p> Post Count: '. $category->count . '</p>';
    	  } //foreach
Viewing 1 replies (of 1 total)
  • 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.