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

如何在ACF Repeater中实现每3个项一组的循环分组?

ACF Repeater 循环分组修复:每3个可见项包裹到.course_block容器

你的问题出在计数逻辑和渲染逻辑脱节:原代码用$count对所有Repeater行计数,但部分行因日期过期被过滤不显示,导致分组容器的开闭时机和实际显示的项不匹配,最终出现嵌套异常。

下面是修正后的代码,核心是只对实际渲染的项进行计数,以此控制.course_block容器的创建和闭合:

<?php
$course_reference = get_field('course-reference-number');
$program_id = get_field('course-program-id');

if( have_rows('course_month_out') ):
    while( have_rows('course_month_out') ) : the_row();

        if( have_rows('course_schedule_row_dates') ):
            $visible_count = 0; // 仅统计实际显示的项
            $is_block_open = false; // 标记容器是否已打开

            while( have_rows('course_schedule_row_dates') ) : the_row();
                
                $course_date_selector = get_sub_field('course_date_selector');
                $course_date_url = date('d-m-y', strtotime($course_date_selector));
                $current_date_field = get_sub_field('course_date_selector', false, false);
                $currentDateTime = date('Ymd');

                // 只处理未过期的日期
                if($current_date_field >= $currentDateTime) {
                    // 每3个项的第一个,打开新容器
                    if ($visible_count % 3 == 0) {
                        ?>
                        <div class="course_block">
                        <?php 
                        $is_block_open = true;
                    }

                    // 输出分隔符(除了第一个显示的项)
                    if($visible_count > 0) {
                        echo ",";
                    }
                    ?>
                    <a href="https://ei.aimsapp.com/onlineapp/LandingPage.aspx?strProgID=<?php echo $program_id; ?>&strIntakeID=<?php echo $course_date_url . "-" . $course_reference . "-01"; ?>" target="_blank">
                        <?php echo $course_date_selector; ?>
                    </a>
                    <?php

                    // 每3个项的第三个,闭合容器
                    if ($visible_count % 3 == 2) {
                        ?>
                        </div>
                        <?php 
                        $is_block_open = false;
                    }

                    $visible_count++;
                }
            endwhile;

            // 循环结束后,检查是否有未闭合的容器
            if ($is_block_open) {
                ?>
                </div>
                <?php
            }
        endif;
    endwhile;
endif;
?>

关键修改说明:

  • 新增$visible_count:仅对实际渲染的未过期日期项计数,确保分组逻辑和显示内容匹配
  • 新增$is_block_open:标记容器状态,避免循环结束后遗留未闭合的标签
  • 将容器开闭逻辑移到未过期日期的判断块内:只有当项要显示时才触发分组,避免空容器或错误闭合
  • 分隔符逻辑改为用$visible_count判断:原代码的get_row_index()会包含被过滤的行,导致分隔符位置错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:25:14