I need to divide the blog into three columns. For that, I wrote:
<?php $i = 0; ?>
<div class="onethird">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 3) == 0) : $wp_query->next_post(); else : the_post(); ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
<?php $i = 0; rewind_posts(); ?>
<div class="onethird">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 3) == 1) : $wp_query->next_post(); else : the_post(); ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
<?php $i = 0; rewind_posts(); ?>
<div class="onethird last">
<?php if (have_posts()) : while(have_posts()) : $i++; if(($i % 3) == 2) : $wp_query->next_post(); else : the_post(); ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
I’m certain it’s very bad code, but it was the best I could come up with. Then, I noticed the duplicate post problems. Again, after lot of googling, wrong:
<?php $i = 0; $dupe = array(); ?>
<div class="onethird">
<?php if (have_posts()) : while(have_posts()) : $i++; if( (($i % 3) == 0) && (!in_array($post->ID, $dupe)) ) : $wp_query->next_post(); else : the_post(); ?>
<?php $dupe[] = $post->ID; echo $post->ID ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
<?php $i = 0; rewind_posts(); ?>
<div class="onethird">
<?php if (have_posts()) : while(have_posts()) : $i++; if( (($i % 3) == 1) && (!in_array($post->ID, $dupe)) ) : $wp_query->next_post(); else : the_post(); ?>
<?php $dupe[] = $post->ID; echo $post->ID ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
<?php $i = 0; rewind_posts(); ?>
<div class="onethird last">
<?php if (have_posts()) : while(have_posts()) : $i++; if( (($i % 3) == 2) && (!in_array($post->ID, $dupe)) ) : $wp_query->next_post(); else : the_post(); ?>
<?php $dupe[] = $post->ID; echo $post->ID ?>
<?php get_template_part( 'content', 'category' ); ?>
<?php endif; endwhile; endif; ?>
</div>
Now it just disregards the counter, and the in_array, and display all posts in all three columns.
If anyone has a better solution for displaying posts in three columns, that would be welcome too!
Three loops seem a bit complicated for what you are trying to achieve.
I would get the total number of posts –
wp_count_posts()– and divide it by 3 (round up) to get the number of posts per column.Then you only have to loop once and you add
</div><div class='onethird'>whenever the remainder of your counter$idivided by the number of posts per column is0.Something like: