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

WooCommerce单产品页面显示购物车中已添加商品数量

在WooCommerce单产品页面显示当前商品的购物车数量

你可以修改现有代码,通过WooCommerce的购物车对象获取当前商品在购物车中的数量,然后插入到文本中间。具体代码如下:

add_action('woocommerce_before_add_to_cart_form', 'gripsquantity', 5);
function gripsquantity(){ 
    // 获取当前产品ID
    $product_id = get_the_ID();
    // 获取购物车中所有商品的数量数组
    $cart_item_qtys = WC()->cart->get_cart_item_quantities();
    // 取出当前商品的购物车数量,默认0(如果未添加)
    $current_qty = isset($cart_item_qtys[$product_id]) ? $cart_item_qtys[$product_id] : 0;
    
    // 输出带数量的文本
    echo 'Choose ' . $current_qty . ' Grips';
}

代码说明:

  • get_the_ID():获取当前单产品页面的产品ID
  • WC()->cart->get_cart_item_quantities():返回购物车中所有商品的ID与对应数量的关联数组
  • 用三元运算符处理购物车中无当前商品的情况,默认显示0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:05:23