'Create a row each third post
I'm working on the search results output for Wordpress website and would like to split a row each third post. Here is what I have at the moment:
<?php if ( have_posts() ) : ?>
<div class="post-wrapper">
<?php
while ( have_posts() ) :
the_post();
?>
<?php get_template_part( 'partials/content', get_post_format() ); ?>
<?php endwhile; ?>
</div>
<?php else : ?>
<?php get_template_part( 'partials/content', 'none' ); ?>
<?php endif; ?>
Now it gets all results but just in one column and I'd like to have three columns. Theme is using Bootstrap so all I need is to add a 'row' each third post but I just can't figure out how to implement this into the PHP template as above. Can somebody help me?
Solution 1:[1]
Try this for inspiration. Outputs:
0
1
2
-- BREAK --
3
4
5
-- BREAK --
6
7
8
-- BREAK --
9
Code:
<?php
// Loop 10 times.
for ($i = 0; $i < 10; $i++)
{
// If $i MOD 3 evaluates to zero, then we've reached the end of a group of three items.
// Skip when $i is zero, unless you want to show a break before any output.
if ($i && !($i % 3))
// Output a row separator
echo "-- BREAK --\n";
// Output a row with some column values.
echo "$i\n";
}
Solution 2:[2]
Group every 3 posts in one row. Checking the total number of posts avoids a new div in the last element.
$loop_posts = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'no_found_rows' => true,
)
);
$count = 1;
$found_posts= $loop_posts->post_count;
if ($loop_posts->have_posts()) :
echo '<div class="row">';
while ( $loop_posts->have_posts() ) : $loop_posts->the_post(); ?>
<?php
get_template_part( 'includes/news_element', get_post_format() );
if($count % 3==0 && $count <= $found_posts){
echo '</div><div class="row">';
}
$count++;
?>
<?php
endwhile;
echo '</div>';
wp_reset_postdata();
endif;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ro Achterberg |
| Solution 2 | RFerreira |
