如何修复ACF Repeater Block代码使其在前端正常渲染?
解决ACF Pro Repeater Block前端不渲染的问题
看你提供的代码,能发现几个核心问题,咱们一步步来修正:
1. 字段获取逻辑放错了位置
你现在把get_sub_field的代码写在了Block注册的主文件里,但**get_sub_field必须在Repeater字段的循环内部调用**,而且应该放在指定的render_template对应的模板文件(也就是building-projects.php)里,注册Block的代码只负责定义Block的基本信息,字段渲染逻辑要单独分离到模板文件中。
2. 修正后的完整代码示例
第一步:保留正确的Block注册代码
把注册逻辑留在主文件里,去掉多余的字段获取代码:
add_action('acf/init', 'my_acf_init_block_types'); function my_acf_init_block_types() { if( function_exists('acf_register_block_type') ) { acf_register_block_type(array( 'name' => 'building_projects', 'title' => __('Building Projects'), 'description' => __('A custom block for Building Projects.'), 'render_template' => get_template_directory() . '/template-parts/blocks/building-projects/building-projects.php', 'category' => 'formatting', 'icon' => 'building', 'keywords' => array( 'building', 'nodaco' ), )); } }
第二步:在模板文件中编写Repeater渲染逻辑
打开building-projects.php,写入以下代码(注意替换实际的子字段名):
<?php // 检查Repeater字段是否存在数据 if( have_rows('project_descriptions') ): // 循环遍历Repeater的每一行数据 while( have_rows('project_descriptions') ) : the_row(); // 获取当前行的子字段值,这里假设子字段名为"description_content",请根据你实际的字段名修改 $sub_text = get_sub_field('description_content') ?: 'Detail Project here...'; // 安全输出内容(用esc_html做XSS防护) echo '<p>' . esc_html($sub_text) . '</p>'; endwhile; else : // 没有数据时显示默认提示 echo '<p>Detail Project here...</p>'; endif; ?>
3. 关键注意事项
- 确认你的Repeater字段键确实是
project_descriptions,子字段的键要和get_sub_field里的参数完全匹配,字段名写错是最常见的坑! get_sub_field必须在have_rows()和the_row()的循环内部使用,它依赖当前循环的行上下文才能正确取值。- 后台编辑页面要确保已经给这个Block添加了Repeater数据,空数据当然不会在前端显示内容。
- 输出内容时尽量用
esc_html()这类安全函数,避免出现安全风险。
内容的提问来源于stack exchange,提问作者user7039658
相关产品推荐
相关产品推荐

