Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active July 13, 2023 01:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronsummers/fcaa4379cdeee9c6dbb7bd7775e73e74 to your computer and use it in GitHub Desktop.
Save aaronsummers/fcaa4379cdeee9c6dbb7bd7775e73e74 to your computer and use it in GitHub Desktop.
Splitting post loop with array chunk, WordPress.
<?php
$args = array(
'post_type' => array('post'),
'posts_per_page' => 16
);
?>
<?php
/**
* https://developer.wordpress.org/reference/functions/get_posts/
* https://codex.wordpress.org/Template_Tags/get_posts
*/
$posts = get_posts( $args );
if ( !empty($posts) ) :
?>
<section class="main-section">
<?php foreach (array_chunk($posts, 4, true) as $posts) : ?>
<div class="chunk-wrapper">
<?php foreach( $posts as $post ) : setup_postdata($post); ?>
<div class="post-item">
<?php the_title('<h3>','</h3>'); ?>
<?php echo wpautop(wp_trim_words( get_the_content(), $num_words = 20, $more = null )); ?>
</div><!-- /.post-item -->
<?php endforeach; // foreach( $posts as $post ) : setup_postdata($post); ?>
</div><!-- /.chunk-wrapper -->
<?php endforeach; // foreach (array_chunk($posts, 4, true) as $posts) :
wp_reset_postdata(); ?>
</section><!-- /.main-section -->
<?php endif; // if ( !empty($posts) ) : ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment