You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ACF构建的Gutenberg区块中拆分WordPress自定义文章类型循环?

在Gutenberg区块中结合ACF拆分自定义文章类型循环实现Tailwind网格布局

我需要在Gutenberg区块中使用Advanced Custom Fields(ACF)展示指定自定义文章类型的内容,同时要拆分循环实现不同的文章布局——用TailwindCSS制作具有不同行高、列高的文章网格(参考下方目标布局图),且不依赖外部CSS文件。

之前我使用过一个拆分WordPress循环的函数,在常规模板中可以正常工作,但在Gutenberg区块内无法生效,同时该函数不支持自定义文章类型。

原函数代码(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++;
    }
}

在常规模板(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 } ?>

我尝试在Gutenberg区块模板(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 ?>

希望得到以下帮助:

  • 在Gutenberg区块内高效拆分WordPress循环(无需计数器)
  • 结合自定义文章类型与ACF实现WordPress循环拆分

目标文章网格布局

内容的提问来源于stack exchange,提问作者Nikolai Lehbrink

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:30:55