0

The following lists the latest 5 blog posts, and then displays an ad, then continues off listing the remaining blog posts.

while ( have_posts() ) :
    the_post();

    if( 5 > $wp_query->current_post ):
        the_title();
    else :
        break;
    endif;

endwhile;

echo 'My Ad';

while ( have_posts() ) :
    the_post();

    the_title();

endwhile;

Trying to update it so it does first 5 posts, AD, next "4" posts, then another AD, then remaining posts. So far no luck. Below is what I tried. It displays the first 5 latest posts, displays the ad, but then when it starts showing the next 4 latest posts it skips post number 6 and starts at post number 7 unfortunately. Also after the second ad rather than continuing with the remaining posts, it starts the loop all over again.

            <?php while ( have_posts() ) :
                    the_post();

                    if( 5 > $wp_query->current_post ): ?>
                     <?php the_title(); ?>
              <?php else :
                        break;
                    endif;

                  endwhile; ?>

                 Fixed Graphic

                 <?php while ( have_posts() ) :
                         the_post();

                         if( 10 > $wp_query->current_post ): ?>
                             <?php the_title(); ?>
                  <?php else :
                             break;
                         endif;

                       endwhile; ?>

                  Fixed Graphic

                 <?php // remaining posts
                    while ( have_posts() ) :
                        the_post();

                        the_title();

                    endwhile; ?>
0

As stated by the codex, have_posts starts, steps through or rests the loop. check codex here. In your code, when entering the second or n-th while, the posts loop is already started, so it steps to the next post, that's why it skips 6th element and starts over on the last while loop. I would suggest you to include your ad code inside else -break branch.

1
  • Another solution would be to decrement the current_post property of $wp_query before each additional while loop. Though about this while I had a look through wp core Wp_Query class: it uses current_post property to decide what to do next inside have_posts method. Although untested, I think this solution would also do what you want. – theodorhanu Jan 18 '17 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.