1

How can I add a break dynamically after 5 posts have been display to create a list of post titles?

<div class="col-sm-2">
          <ul>
            <?php
                $args = array( 'post_type' => 'custom-post-type' );
                $query = new WP_Query( $args );

                  if ( have_posts() ) : while ( $query ->have_posts() ) : $query ->the_post();
                  ?>

            <li><?php the_title(); ?></li>

                <?php $query_count = $query ->current_post + 1; ?>
                <?php if ( $query_count % 5 == 0): ?>

          </ul>
        </div>
        <div class="col-sm-2">
          <ul>

              <?php endif; ?> 

           <?php endwhile; endif; wp_reset_postdata(); ?>
          </ul>
        </div>

At the moment first 10 posts are displayed correctly with the remaining posts not being displayed. There is a empty third div element following the first 2 divs but no posts. I can't see what I've missed. Thanks for any feedback.

1

You're basically checking ( $query->current_post + 1 ) % 5 == 0. For the last post, where $query->current_post equals 9, this also returns true, as 10 % 5 equals 0. Thus, another closing and opening of a div and a ul is outputted.

You can prevent this by checking whether there are any posts left to display (using $query->post_count, the number of posts being displayed):

if ( $query_count % 5 == 0 && $query_count < $query->post_count )
3
  • Thanks for you help. The empty div is gone. Second challenge is the missing posts. I added 'posts_per_page' => 0 but the posts do not show. Any thoughts? – Gram3000 Jun 11 '14 at 17:53
  • Have you tried using posts_per_page => -1? Using posts_per_page => 0 will use the number of posts per page specified in your Reading settings. – engelen Jun 12 '14 at 8:03
  • That was it! I didn't understand that 0 was connected to Reading settings. Thanks! – Gram3000 Jun 12 '14 at 15:28

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.