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

WooCommerce非变体商品自定义购物车数据显示时变体商品报错排查

WooCommerce购物车变体商品报错排查与修复

尝试使用woocommerce_get_item_data钩子在购物车中为非变体商品显示自定义数据,已添加判断条件,但变体商品仍出现报错。

用户代码

add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
    
    if ( empty($cart_item["variation"])) {
    
            $my_data = $cart_item["my_data"];
            $data_array = array();
        
    $data_array[] = array(
                    'key'       => "Some Key",
                    'value'       => "Some Value",
                );
    
return $data_array;
        
        }
}

变体商品报错信息

Warning: Invalid argument supplied for foreach() in /data/0/b/0b142c6f-d1fc-41f2-b82d-95dd95505032/xxx.sk/sub/shop/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 3741

Warning: count(): Parameter must be an array or an object that implements Countable in /data/0/b/0b142c6f-d1fc-41f2-b82d-95dd95505032/xxx.sk/sub/shop/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 3752

问题根源

函数仅在非变体商品的条件分支里返回了数组,当处理变体商品时,条件不满足,函数默认返回null。而WooCommerce后续会对该钩子的返回值执行foreach循环和count操作,null不属于可遍历/计数的类型,因此触发报错。

修复代码

确保函数在所有分支都返回数组:非变体商品返回自定义数据数组,变体商品返回原有$item_data参数(保留原有逻辑)。

add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
    
    if ( empty( $cart_item["variation"] ) ) {
        $data_array = array();
        $data_array[] = array(
            'key'   => "Some Key",
            'value' => "Some Value",
        );
        return $data_array;
    }
    
    // 变体商品直接返回原有数据,保证始终返回数组
    return $item_data;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:25:42