Skip to content

Instantly share code, notes, and snippets.

@jeffreyvr
Last active October 28, 2020 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreyvr/911a627be078fabf6d707651156903d8 to your computer and use it in GitHub Desktop.
Save jeffreyvr/911a627be078fabf6d707651156903d8 to your computer and use it in GitHub Desktop.
Splitting the WordPress loop for alternate grids
<div class="grid">
<?php
posts_from_loop( 2, function() {
get_template_part( 'partials/post-w50' );
});
?>
</div>
<div class="grid">
<?php
posts_from_loop( 3, function() {
get_template_part( 'partials/post-w33' );
});
?>
</div>
<?php while ( have_posts() ) {
the_post();
?>
<?php get_template_part( 'partials/post-w100' ); ?>
<?php } ?>
<?php
/**
* Fetch a specific amount of posts from the main query.
*
* @param integer $amount Amount of posts.
* @param callback $callback A callback function.
* @return void
*/
function posts_from_loop( $amount, $callback ) {
global $wp_query;
while ( ( $count < $amount ) && ( $wp_query->current_post + 1 < $wp_query->post_count ) ) {
$wp_query->the_post();
$callback();
$count++;
}
}
<?php
$count = 0;
while ( have_posts() ) {
the_post();
if ( $count == 0 || $count == 2 ) {
echo '<div class="grid">';
}
if ( $count <= 1 ) {
get_template_part( 'partials/post-w50' );
} elseif ( $count > 1 && $count <= 4 ) {
get_template_part( 'partials/post-w33' );
} else {
get_template_part( 'partials/post-w100' );
}
if ( $count == 1 || $count == 4 ) {
echo '</div>';
}
$count++;
}
@jeffreyvr
Copy link
Author

Example of the grid:

grid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment