Created
April 22, 2016 13:35
-
-
Save brettshumaker/7c3e111771c9325ab7f49e2a28bfdd95 to your computer and use it in GitHub Desktop.
This is some boilerplate code to take the content of a WP Query and split the posts into relatively evenly distributed rows and columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$args = array( | |
'post_type' => 'post', | |
'posts_per_page' => -1, | |
); | |
$posts_loop = new WP_Query( $args ); | |
if ( $posts_loop->have_posts() ) : | |
// Initialize Output | |
$output = ''; | |
$started_last_row = false; | |
// Set current counts to 1 | |
$cur_row = $cur_col = $cur_item_count = 1; | |
// Get total items in query | |
$total_items_count = $posts_loop->found_posts; | |
// Set number of rows | |
$num_rows = 4; | |
// Set number of columns | |
$num_cols = 3; | |
$grid_markup = (int) 12 / $num_cols; | |
$row_start = '<div class="row">'; | |
$row_end = '</div>'; | |
$col_start = '<div class="columns medium-' . $grid_markup . '">'; | |
$col_end = '</div>'; | |
// Determine the number of items per column | |
$items_per_col = ceil( ( $total_items_count / $num_rows ) / $num_cols ); | |
// Initialize loop index | |
$i = 1; | |
while ( $posts_loop->have_posts() ) : $posts_loop->the_post(); | |
// Check to see if we're in the last row, we might need to do some balancing | |
if ( $cur_row == $num_rows && ! $started_last_row ) { | |
// Count the items remaining | |
$items_remaining = $total_items_count - $i + 1; | |
// Determine the new number of items per column | |
$items_per_col = ceil( $items_remaining / $num_cols ); | |
// Signal that we don't need to do this again. | |
$started_last_row = true; | |
} | |
if ( 1 == $cur_row && 1 == $cur_item_count ) { | |
// START ROW | |
$output .= $row_start; | |
} | |
if ( 1 == $cur_item_count ) { | |
// START COL | |
$output .= $col_start; | |
} | |
// echo item content | |
$output .= "here's my item content"; | |
if ( $cur_item_count == $items_per_col ) { | |
// END COL | |
$output .= $col_end; | |
$cur_item_count = 0; | |
$cur_row++; | |
} | |
if ( $cur_row == $num_cols + 1 ) { | |
// END ROW | |
$output .= $row_end; | |
$cur_row++; | |
$cur_row = 1; | |
$cur_item_count = 0; | |
} | |
// Check to see if we're at the end of our items and close everything | |
if ( $cur_row == $num_rows && $i == $total_items_count ) { | |
// END COL | |
$output .= $col_end; | |
// END ROW | |
$output .= $row_end; | |
} | |
$cur_item_count++; | |
$i++; | |
endwhile; | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment