Group Posts in Pairs in WordPress Custom Query
Sometimes, when you build a website using WordPress, you may want to show posts in a clean layout. For example, imagine you are creating a blog or product page where you want to show 2 items in one row. But by default, posts come one after another, not in groups.
To do this, you need to group every 2 posts inside a single container. In this article, we will show you a simple way to do this using a counter in a custom query loop. This method helps you control the layout easily without using any extra plugins.
<?php
// Define your custom query
$args = array(
'post_type' => 'post', // Change to your post type
'posts_per_page' => -1, // Adjust the number of posts
);
$query = new WP_Query($args);
if ($query->have_posts()) :
$counter = 0; // Initialize a counter
echo '<div class="outer-container">'; // Optional: Wrap everything in an outer container
while ($query->have_posts()) : $query->the_post();
// Open a new div for every 2 posts
if ($counter % 2 == 0) {
echo '<div class="inner-container">'; // Start a new container
}
// Display your post content here
?>
<div class="post-item">
<h2><?php the_title(); ?></h2>
<div class="post-excerpt">
<?php the_excerpt(); ?>
</div>
</div>
<?php
$counter++; // Increment the counter
// Close the div after every 2 posts
if ($counter % 2 == 0) {
echo '</div>'; // Close the container
}
endwhile;
// Close the last div if it's not closed yet
if ($counter % 2 != 0) {
echo '</div>';
}
echo '</div>'; // Close the outer container
else :
echo '<p>No posts found.</p>';
endif;
wp_reset_postdata();
?>