求助:修复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');
补充说明
- 用
get_sub_field()替代the_sub_field(),正确获取字段值并赋值给变量 - 将渲染逻辑移入
while循环内,确保每条Repeater数据都被处理 - 新增
ob_start()初始化输出缓冲,配合ob_get_clean()正确返回短码内容 - 根据
date_fin和heure字段是否有值,动态拼接对应文本,实现示例中的两种展示格式 - 若原代码中
$du/$au/$a字段是用来存储多语言文本的,可调整代码从这些字段取值,替换当前硬编码的英文文本
内容的提问来源于stack exchange,提问作者carosch
相关产品推荐
相关产品推荐

