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

ACF使用技巧:如何仅获取Repeater Field重复字段的第一行数据

解决方案

方法1:修正现有循环写法

你尝试调整的代码存在PHP标签嵌套错误、break语句位置不对的问题,修正后可正常实现只取第一个非空的image值:

<?php if( have_rows('images') ): ?>
<?php
$active = 'active';
while ( have_rows('images') ) : the_row();
    $image = get_sub_field('image');
    if(empty($image)) {
        continue;
    }
?>
    <img src="<?php echo get_template_directory_uri(); ?>/files/images/<?php the_sub_field('image'); ?>" class="img-fluid is-slider-item" />
<?php 
    $active = '';
    // 匹配到第一个非空值后直接终止循环
    break;
endwhile;
?>
<?php endif; ?>

方法2:数组直接取值(更高效)

不需要循环遍历行,直接将Repeater字段作为完整数组读取,直接提取目标值即可,代码更简洁:

兼容跳过空值版本

<?php
// 直接获取整个repeater字段的数组数据
$images = get_field('images');
$active = 'active';
if (!empty($images)) {
    // 遍历查找第一个非空的image值
    foreach ($images as $item) {
        $image = $item['image'] ?? '';
        if (!empty($image)) {
            ?>
            <img src="<?php echo get_template_directory_uri(); ?>/files/images/<?php echo esc_html($image); ?>" class="img-fluid is-slider-item" />
            <?php
            $active = '';
            break;
        }
    }
}
?>

简化版本(确认第一个子字段不会为空时使用)

<?php
$images = get_field('images');
if (!empty($images[0]['image'])) {
    ?>
    <img src="<?php echo get_template_directory_uri(); ?>/files/images/<?php echo esc_html($images[0]['image']); ?>" class="img-fluid is-slider-item" />
    <?php
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:39:03