Title: Run WP_Query Within a Loop
Last modified: August 21, 2016

---

# Run WP_Query Within a Loop

 *  Resolved [Mstoic Themes](https://wordpress.org/support/users/mstoic/)
 * (@mstoic)
 * [12 years, 4 months ago](https://wordpress.org/support/topic/run-wp_query-within-a-loop/)
 * On my index page, I want to list 5 posts from each category that has more than
   5 posts. Do I have to put the code again and again or there can be a loop to 
   run WP_Query for every category? Also, is there any other better way of dong 
   that?

Viewing 1 replies (of 1 total)

 *  Thread Starter [Mstoic Themes](https://wordpress.org/support/users/mstoic/)
 * (@mstoic)
 * [12 years, 4 months ago](https://wordpress.org/support/topic/run-wp_query-within-a-loop/#post-4524413)
 * Solved Myself:
 * $arr = array (
    array (‘category_name’ => ‘youtube’, ‘posts_per_page’ => ‘4’),
   array (‘category_name’ => ‘Google’, ‘posts_per_page’ => ‘3’), array (‘category_name’
   => ‘Dropbox’, ‘posts_per_page’ => ‘2’), array (‘category_name’ => ‘Windows’, ‘
   posts_per_page’ => ‘1’) );
 * foreach ($arr as $args) {
    $the_query = new WP_Query( $args ); if ( $the_query-
   >have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();
   echo ‘<p>’ . get_the_title() . ‘</p>’; //echo ‘<div class=”entry”>’ . get_my_excerpt(
   50) . ‘</div>’; endwhile; echo ‘<hr>’; wp_reset_postdata(); else: echo ‘<p>’ .
   _e( ‘Sorry, no posts matched your criteria.’ ) . ‘</p>’; endif; }

Viewing 1 replies (of 1 total)

The topic ‘Run WP_Query Within a Loop’ is closed to new replies.

## Tags

 * [loop](https://wordpress.org/support/topic-tag/loop/)
 * [wp_query](https://wordpress.org/support/topic-tag/wp_query/)

 * In: [Fixing WordPress](https://wordpress.org/support/forum/how-to-and-troubleshooting/)
 * 1 reply
 * 1 participant
 * Last reply from: [Mstoic Themes](https://wordpress.org/support/users/mstoic/)
 * Last activity: [12 years, 4 months ago](https://wordpress.org/support/topic/run-wp_query-within-a-loop/#post-4524413)
 * Status: resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
