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

如何在functions.php中创建短代码调用ACF repeater字段

实现结论

该需求完全可实现,你现有代码的核心问题是WordPress短代码回调函数不支持直接echo输出内容,直接打印会导致内容显示位置错乱,必须将待展示的内容拼接后作为返回值返回。

完整实现代码

把你主题目录下functions.php文件里的短代码代码替换为以下内容即可:

function get_car_parts() {
    // 开启输出缓冲捕获模板内容,无需改写你已写好的repeater循环逻辑
    ob_start();

    if ( have_rows( 'car_parts' ) ) : ?>
        <div class="car-parts-wrapper">
        <?php while ( have_rows( 'car_parts' ) ) : the_row(); ?>
            <div class="car-engine-item">
                <?php the_sub_field( 'car_engine' ); ?>
            </div>
        <?php endwhile; ?>
        </div>
    <?php else : ?>
        <p>暂无配件信息</p>
    <?php endif;

    $output = ob_get_clean();
    return $output;
}
add_shortcode( 'show-car-parts', 'get_car_parts' );
使用方法

在Gutenberg编辑器中添加「短代码」区块,在区块内输入[show-car-parts],更新文章后即可在对应位置看到repeater字段的输出内容。

注意事项
  • 短代码默认会自动读取当前所属文章的ACF字段数据,无需额外传文章ID
  • 如果需要调用其他文章、ACF选项页的repeater字段,可给have_rows()传入第二个参数指定来源:比如调用ID为45的文章字段写为have_rows( 'car_parts', 45 ),调用站点选项页字段写为have_rows( 'car_parts', 'option' )
  • 如果前台无输出,优先检查当前文章是否已经给car_parts字段添加了有效数据,确认ACF字段的位置规则匹配当前文章类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:39:14