Reputation: 5013
I need to separate WordPress posts loop in to 2 columns , left and right.
Currently I am doing this with 2 separate loops but would like to make it with one if possible.
<div class="left-side">
<?php
$row_start = 1;
while ( have_posts() ) : the_post();
if( $row_start % 2 != 0) {// odd
get_template_part( 'blog','item');
}
++$row_start;
endwhile;
?>
</div>
<div class="right-side">
<?php
$row_start = 1;
while ( have_posts() ) : the_post();
if( $row_start % 2 == 0) {// even
get_template_part( 'blog','item');
}
++$row_start;
endwhile;
?>
</div>
Any help is appreciated!
Upvotes: 2
Views: 1776
Reputation: 21236
Move the loops into a separate template files.
Create two files in your themes directory, one named posts-odd.php
and the other named posts-even.php
and add the post loops respectively, i.e:
posts-odd.php
:
<?php
$row_start = 1;
while ( have_posts() ) : the_post();
if( $row_start % 2 != 0) {// odd
get_template_part( 'blog','item');
}
++$row_start;
endwhile;
?>
posts-even.php
:
<?php
$row_start = 1;
while ( have_posts() ) : the_post();
if( $row_start % 2 == 0) {// even
get_template_part( 'blog','item');
}
++$row_start;
endwhile;
?>
In your main template you can now use get_template_part
function to include the partial template into your main template:
<div class="left-side">
<?php get_template_part('posts', 'odd') ?>
</div>
<div class="right-side">
<?php get_template_part('posts', 'even') ?>
</div>
If you're displaying the odd and even posts in various places this will give you the benefit of only having to define the loop templates once.
https://developer.wordpress.org/reference/functions/get_template_part/
Upvotes: 2
Reputation: 11670
Not easy but possible.
<?php
$i = 0;
$column = array();
$column[1] = $column[2] = '';
if (have_posts()) :
while (have_posts()) :
the_post();
$i++;
$column[$i] .= '<div class="'.esc_attr(implode(' ', get_post_class())) .'">';
$column[$i] .= '<div class="post_inner">
'.get_the_content().'
</div>
</div>';
$i = ($i==2) ? 0 : $i;
endwhile; ?>
<div id="grid_posts">
<div class="span6"><?php echo $column[1]?></div>
<div class="span6"><?php echo $column[2]?></div>
</div>
<?php else: ?>
<p><?php esc_html_e('No posts were found. Sorry!', 'mytheme'); ?></p>
<?php endif; ?>
Basically you create columns array and put your contents in there in two keys (1 and 2), and every 2 posts you put in one column, and keep increasing the counter to 2 and resetting it once it gets to 2. So you keep filling the array with posts - first to key 1 and then to key 2 and so on.
Then you just output those two into 2 columns (span6
in my case).
Hope this helps.
Upvotes: 1