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

求助:修复ACF Repeater字段短码显示的WordPress报错问题

修复ACF Repeater字段短码的严重错误

原代码的核心问题

  • 误用the_sub_field():该函数直接输出字段内容,无法赋值给变量,必须改用get_sub_field()获取字段值
  • 输出逻辑位置错误:渲染代码放在while循环外部,只能获取最后一条Repeater数据,所有条目需在循环内处理
  • 缺少输出缓冲初始化:调用ob_get_clean()前未执行ob_start(),触发PHP错误
  • 语法错误:echo语句末尾未闭合字符串引号,破坏语法结构
  • 未实现条件显示逻辑:未根据字段是否有值动态拼接"from""to""at"等文本

修复后的完整代码

// ########### 调用ACF Repeater字段 lieu_date_heure
function get_lieu_date_heure() {
    ob_start(); // 开启输出缓冲

    if (have_rows('lieu_date_heure')):
        while (have_rows('lieu_date_heure')): the_row();
            $ville = get_sub_field('ville');
            $date_debut = get_sub_field('date_debut');
            $date_fin = get_sub_field('date_fin');
            $heure = get_sub_field('heure');

            // 构建内容字符串
            $content = $ville . ', ';
            
            // 处理日期部分
            if ($date_fin) {
                $content .= 'from ' . $date_debut . ' to ' . $date_fin;
            } else {
                $content .= $date_debut;
            }
            
            // 处理时间部分
            if ($heure) {
                $content .= ', at ' . $heure;
            }

            // 输出单个条目
            echo '<div class="lieu_date_heure"><p>' . $content . '</p></div>';
        endwhile;
    endif;

    return ob_get_clean(); // 返回缓冲内容并清空
}
add_shortcode('show_lieu_date_heure', 'get_lieu_date_heure');

补充说明

  1. 用get_sub_field()替代the_sub_field(),正确获取字段值并赋值给变量
  2. 将渲染逻辑移入while循环内,确保每条Repeater数据都被处理
  3. 新增ob_start()初始化输出缓冲,配合ob_get_clean()正确返回短码内容
  4. 根据date_fin和heure字段是否有值,动态拼接对应文本,实现示例中的两种展示格式
  5. 若原代码中$du/$au/$a字段是用来存储多语言文本的,可调整代码从这些字段取值,替换当前硬编码的英文文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:57:39