Splitting WordPress Posts Into Sets

Follow @tristarweb

The other day I found the need to split my loop into sets of 4. For example, a div would open at the start of the loop, then close after 4 posts, then open again, and then close at the end; of course, this would carry on in multiples of 4. I needed this for creating a slider with 4 posts in each slide.

In the end I wrote a nice little addition to the WordPress loop that allows you to do exactly that.

  <?php $split = 4; // Split into sets of 4 ?>

  <?php $i = 0; if (have_posts()) : while(have_posts()) : the_post(); ?>

          <?php if($i%$split==0) { /* if counter is multiple of $split, put an opening div */ ?><div class="post-set"><?php } ?>

        <div><?php the_content(); /* Your WordPress Content */ ?></div>

          <?php $i++; if($i%$split==0) { /* if counter is multiple of $split, put an closing div */ ?></div><?php } ?>

  <?php endwhile; endif; ?>

  <?php if($i%$split!=0) { /* put closing div here if loop is not exactly a multiple of $split */ ?></div><?php } ?>

I have commented the above to make it easier to understand, however, it makes it look as though there is more code than there is! Anyway, all you do is set the $split variable to the number of posts you would like to group together; the loop will then see if the counter is currently at a multiple of 4, at which point it would open/close/ignore the div tag.

Try it out for yourself, It could also be a good way of adding even/odd classes to divs.

About James

Hello there, I'm James. I studied Multimedia Design at university. I'm a designer at heart, though I love developing innovative and exciting solutions to web based products.I now specialise in front end web design and bespoke Wordpress powered websites.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter