WP_Query inside an existing wp_query stops next post showing

We can simplify your code and just run one query instead of two. The answer lies in rewinding your loop and rerunning it multiple times. We will use the build in loop counter, $current_post to count our posts. Just remember, this counter starts at 0, and not 1, so post 1 will be 0

So here is what we need to do

  • Query 10 posts instead of doing two loops of five

  • Run the loop and only display the first two posts

  • Rewind our loop, and rerun it and output posts 6-10

  • Rewind our loop again, and rerun the loop once more and display posts 3-5

In code (skeleton only), you can try something like this: (Requires PHP 5.4+ due to new short array syntax ([]), for older versions, replace with old array syntax (array()))

$args = [
    'posts_per_page' => 10
];
$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    // Run the loop the first time to display the first two posts
    while ( $q->have_posts() ) {
        $q->the_post();

        if ( $q->current_post <= 1 ) {

            // Do what you need to do with the first two posts

        } 
    }

    // Rewind the loop
    $q->rewind_posts();
    // Run the loop the second time to display posts 6 - 10

    while ( $q->have_posts() ) {
        $q->the_post();

        if ( $q->current_post >= 5 && $q->current_post <= 9 ) {

            // Do what you need to do with posts 6 - 10

        } 
    }

    // Rewind the loop
    $q->rewind_posts();

    // Run the loop the third time to display posts 3 - 5
    while ( $q->have_posts() ) {
        $q->the_post();

        if ( $q->current_post >= 2 && $q->current_post <= 4 ) {

            // Do what you need to do with posts 3 - 5

        } 
    }
    wp_reset_postdata();
}

Leave a Comment