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

使用ACF Pro的add_row()和add_sub_row()添加嵌套字段遇阻

解决ACF Flexible Content中嵌套Repeater字段的程序化添加问题

你遇到的问题核心是错误地在add_row的数组参数中直接嵌套add_sub_row调用,ACF的嵌套字段需要遵循「先创建父级行,再基于父级行添加子行」的逻辑,不能在父行的数组里直接嵌入子行的函数调用。

正确实现步骤

  1. 先调用add_row添加Flexible Content的布局行,获取返回的新行索引(ACF会返回该行的整数索引,失败则返回false)
  2. 用这个索引构造嵌套Repeater字段的父路径,再调用add_sub_row添加子行

完整可运行代码

// 第一步:添加Flexible Content的background_image_with_content_block布局行
$layout_row_index = add_row('layouts', [
    'acf_fc_layout' => 'background_image_with_content_block',
    'slide_images' => 248,
    'overlay' => 'Blue',
    'include_job_search' => 'No',
    'heading_type' => 'Heading 2',
    'heading' => 'Upload your CV today',
    'content' => 'Upload your CV today, and we will be in touch to help you find your perfect career. Upload your CV today, and we will be in touch to help you find your perfect career.',
], $post_id);

// 检查父行是否添加成功,再处理嵌套的Repeater字段
if ($layout_row_index !== false) {
    // 构造嵌套Repeater的父字段路径:Flexible字段名/行索引/Repeater字段名
    $parent_repeater_path = "layouts/{$layout_row_index}/links";
    
    // 第二步:添加Repeater字段的一行(可多次调用添加多行)
    add_sub_row($parent_repeater_path, [
        // 这里填写Repeater内部的实际字段键,替换成你的真实字段
        'link_colour' => 'White',
        'link_type' => 'external', // 示例:链接类型字段
        'link_target' => '_blank'  // 示例:选择类型字段
    ], $post_id);
}

关键修正点

  • 移除了错误嵌套在add_row数组中的add_sub_row调用,改为分步执行
  • 子行数组中不需要acf_fc_layout(这是Flexible Content布局的标识,Repeater字段不需要)
  • 父字段路径必须遵循{flexible字段名}/{行索引}/{repeater字段名}的格式,ACF才能识别到嵌套的Repeater位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:25:18