I'm running into an issue.. I've written a code inside a loop so that it creates a new box every 3rd iteration in the loop. It does this nicely, however for example if I have 4 items in a full query of returned posts , it breaks on the 4th one because when it resets to 1 again (from creating the end div tags on the 3rd final iteration then it resets back to 1) it doesn't know to create and end to the 2nd box on the 4th post item. Is there a way so that if there is no more posts left in the query to create end div tag even there's only 1 left? If that makes sense..

<?php if($i%3 == 0){ ?>
<div id="featured-boxes">

<div class="itembox hightlighted-front" itemtype="http://schema.org/Person" itemscope="">
    <h1 itemprop="name" class="icon-search-item">Featured Accident Lawyers</h1>

    <div class="itemboxinner">
        <div class="post clearfix">
<?php } ?>

            <?php /*echo "$i" . "<br>"; */?>
            <div class="thumbnail-large box-<?php echo $i; ?>" style="float: left;">
                <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <img
                itemprop="image" src="<?php echo $PPT->Image($post->ID, "url", "&amp;w=180&amp;h=128"); ?>" class="listImage"
                alt="<?php the_title(); ?>" title="<?php the_title(); ?>"/> </a>

                <div class="info"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>

            <?php $i++; ?>

<?php if($i%3 == 0) {  ?>

<?php } ?>

<?php if($i == 3){ ?><div class="clearfix"></div><?php } ?>

1 Answer 1


place a single box opening and closing markup outside the loop, then only close/open a new one when it's every 3rd post and not last by using the built in loop vars current_post and post_count

if( ( ( $your_query->current_post + 1 ) % 3 == 0 )
    && ( $your_query->current_post + 1 ) != $your_query->post_count ){
        // close the box and open a new one.

EDIT - note that we add 1 to current_post in each test, as it starts at 0, not 1.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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