ACF repeater空post object字段加载随机商品的判断条件问题
问题描述
编写了用于商品页展示捆绑销售关联商品的短代码,基础功能运行正常,但存在空字段触发异常加载的问题。
使用的ACF字段为存储Post Object的Repeater字段,字段值存储对应商品的Post ID。故障表现:新增Repeater字段行但未选择关联商品、保存为空值时,前端会加载大量无关随机商品。
异常场景参考:第二个字段新增后未选择内容,页面右侧出现大量无关商品:
现有故障代码如下:
add_shortcode('acf_rlt_products', function(){ $html = ''; $p_id = get_the_ID(); if (function_exists('get_field')) { $rows = get_field('bundled_product_repeater'); if( $rows ) { foreach( $rows as $row ) { if (isset($row['bundled_product'])) { if ($value == get_sub_field('bundled_product')) { $html .= do_shortcode( '[rlt_product product_id="'.$row['bundled_product'].'" p_id="'.$p_id.'"]' ); } } } } } return $html; });
故障原因
原代码存在两处逻辑缺陷:
- 仅判断
bundled_product键是否存在,未校验对应值是否为空。空值传入下游商品查询逻辑时,会触发WordPress默认查询逻辑,返回全量已发布商品,也就是页面上看到的大量随机无关商品 - 循环内的
$value == get_sub_field('bundled_product')属于无效判断:$value变量未定义,且遍历get_field直接返回的Repeater数组时,不需要调用get_sub_field()读取字段,该判断无实际过滤作用,空值会直接透传到下游短代码。
修复代码
替换原有短代码逻辑即可,新增多层校验过滤空值和无效ID:
add_shortcode('acf_rlt_products', function(){ $html = ''; $p_id = get_the_ID(); if (function_exists('get_field')) { $rows = get_field('bundled_product_repeater'); if( $rows ) { foreach( $rows as $row ) { // 多层校验:键存在、值非空、值为合法数字ID if (isset($row['bundled_product']) && !empty($row['bundled_product']) && is_numeric($row['bundled_product'])) { $product_id = intval($row['bundled_product']); // 额外校验商品为已发布状态,过滤回收站/草稿/已删除商品 if (get_post_status($product_id) === 'publish') { $html .= do_shortcode( '[rlt_product product_id="'.$product_id.'" p_id="'.$p_id.'"]' ); } } } } } return $html; });
修复说明
- 新增
!empty()校验直接过滤未选择商品的空Repeater行,从源头阻断空值传入下游逻辑 - 增加ID格式校验与转义,确保传入短代码的是合法整数类型商品ID,避免异常值触发查询错误
- 增加商品状态校验,过滤无效商品ID,避免前端显示不存在的商品占位
- 移除原代码中无效的变量判断与错误的
get_sub_field()调用,直接读取Repeater行数组内容即可,逻辑更简洁高效。
内容的提问来源于stack exchange,提问作者Demian
相关产品推荐
相关产品推荐

