Skip to content

Instantly share code, notes, and snippets.

@koskinenaa
Last active February 28, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save koskinenaa/4d8461116885c0e64d5ca167ae53434d to your computer and use it in GitHub Desktop.
Save koskinenaa/4d8461116885c0e64d5ca167ae53434d to your computer and use it in GitHub Desktop.
Break WP_Query posts into separate columns
<?php
// Custom WP_Query
$args = array();
$my_query = new WP_Query( $args );
if ( $my_query->have_posts() ) :
// Number of columns
$col_count = 3;
// Get post count
$post_count = $my_query->found_posts;
// Count how many posts will go into each column, rounding fractions up
$posts_per_col = ceil( $post_count / $col_count );
$i = 0;
?>
<div class="span_1_of_<?php echo $col_count; ?> col-1 col clr">
<ul>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<?php if ( $posts_per_col == $i ) :
// Reset post counter for new column
// End previous column and start the next one
$i = 0; ?>
</ul> <!-- end posts list -->
</div> <!-- end column -->
<div class="span_1_of_<?php echo $col_count; ?> col-1 col clr">
<ul>
<?php endif; ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li> <!-- end single post -->
<?php
// Increment post counter
$i++;
// End loop
endwhile;
// Reset post data after custom loop has finished
wp_reset_postdata();
?>
</ul> <!-- end posts list -->
</div> <!-- end column -->
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment