I have a question around displaying posts and custom posts in Gutenberg blocks using Advanced Custom Fields. I want to query all posts of a post type, but split the loop as I need different layouts for individual posts. I want to display the posts in a grid that has different rows and column heights (see image below) and not use external css for this, as I'm working with TailwindCSS. For this I would normally use a function that splits the loop, as described here: https://vanrossum.dev/20-splitting-the-wordpress-loop
//functions.php
function posts_from_loop( $amount, $callback ) {
global $wp_query;
$count = 0;
while ( ( $count < $amount ) && ( $wp_query->current_post + 1 < $wp_query->post_count ) ) {
$wp_query->the_post();
$callback();
$count++;
}
}
and use it like the following:
//home.php
<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 } ?>
However, the function does not work inside a Gutenberg block and also not with custom post types. I tried to set it up like the following
//block.php
<?php
$args = array(
'post_type' => 'posts',
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC',
);
$loop = new WP_Query($args);
?>
<?php if ($loop->have_posts()) : ?>
<div class="container mb-2">
<?php
posts_from_loop(1, function () { ?>
<?php get_template_part('template-parts/partials/post', "featured"); ?>
<?php }); ?>
</div>
<div class="container grid grid-cols-1 gap-2 mx-auto md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<?php
posts_from_loop(4, function () {
get_template_part('template-parts/partials/post', 'color');
});
?>
<?php while (have_posts()) {
the_post();
?>
<?php get_template_part('template-parts/partials/post', "image"); ?>
<?php } ?>
</div>
<?php endif ?>
Would be nice, if someone could help me with
The function posts_from_loop
is acting on the global
query, you have a custom one. The quickest fix would be to pass the custom query in as an optional parameter, falling back to the global if not provided (for BC with any code that is already using the function).
function posts_from_loop( $amount, $callback, $query = null ) {
if(!$query) {
global $wp_query;
$query = $wp_query;
}
$count = 0;
while ( ( $count < $amount ) && ( $query->current_post + 1 < $query->post_count ) ) {
$query->the_post();
$callback();
$count++;
}
}
posts_from_loop(
4,
function () {
get_template_part('template-parts/partials/post', 'color');
},
$loop
)