Split WordPress Loop Posts into Groups

In my last project I needed to split the WordPress loop into groups of three posts – so if there are nine posts, every three would be wrapped in a div. You can do this using a counter and checking inside the loop whether it is a multiple of 3, and if so, closing the div. To change the number of posts per group, change the number 3 on line 14. Here is the code:

<?php if ( have_posts() ) :
	$i = 0;
	while ( have_posts() ) : the_post();
		if ( $i % 3 == 0 ) { ?>
			<div>
	<?php } ?>
			<div class="single_item">
				<h2>
					<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>
					</a>
				</h2>
			</div>
	<?php $i ++;
		if ( $i % 3 == 0 ) { ?>
			</div>
	<?php } ?>

	<?php endwhile; ?>
	<?php
	if ( $i % 3 != 0 ) { ?>
		</div>
	<?php } ?>

<?php endif; ?>

For more loop customization, see Remove a Category from the Main Loop.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!