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

如何修改WooCommerce短代码以统计父产品所有变体的购物车总数量?

解决WooCommerce短代码统计父产品所有变体总数量的问题

你的问题出在数量赋值逻辑上:当前代码每次匹配到对应父产品ID的购物车项时,会直接用当前变体的数量覆盖之前的$qty值,所以最终只显示最后一个添加的变体数量。要实现累加所有变体数量,只需要把赋值操作改成累加操作即可。

修改后的完整代码

if( !function_exists('in_cart_product_quantity') ) {
    function in_cart_product_quantity( $atts ) {

        $atts = shortcode_atts(array('id' => ''), $atts, 'cart_qty_badge');
        if( empty($atts['id'])) return; 

        if ( WC()->cart ) { 
           $qty = 0; 
            foreach (WC()->cart->get_cart() as $cart_item) {
                // 匹配父产品ID时,累加当前购物车项的数量
                if($cart_item['product_id'] == $atts['id']) {
                    $qty += $cart_item['quantity'];
                }
            }
            return $qty;
        }
        return;
    }
    add_shortcode( 'cart_qty_badge', 'in_cart_product_quantity' );
}

关键修改点

把原来的$qty = $cart_item['quantity'];改为$qty += $cart_item['quantity'];:

  • =是直接赋值,会覆盖之前的数值
  • +=是累加操作,把当前变体的数量加到总数量里

这样无论购物车中有多少个该父产品的变体,都会把所有变体的数量相加,最终返回父产品的总购物车数量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:32:46