Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress From Bootstrap to WordPress Create Bootstrap Styled Theme Templates Creating a Portfolio Landing Page

Graeme Ellis
Graeme Ellis
13,439 Points

query loop not displaying all available posts

I've used a technique employed by Zac in this bootstrap to wp lessons to break posts into columns for a list. My problem is if I have 10 posts the code will create an empty div with no posts. I'm not sure why it doesn't loop again and display all the post available?

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

                    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; wp_reset_postdata(); ?>
          </ul>
        </div>

3 Answers

Graeme Ellis
Graeme Ellis
13,439 Points

Got some help at wordpress.stackexchange.com See the full discussion.

Needed to add:

if ( $query_count % 5 == 0 && $query_count < $query->post_count )

This removes the extra div and ul

posts_per_page => -1 will display all the posts for that query. '0' will display the amount within the reading settings.

Graeme Ellis
Graeme Ellis
13,439 Points

I added an if statement which is a good idea. Should have had that there. Unfortunately it didn't fix the loop from showing all the posts available.

    <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>

updated code.