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

如何在WooCommerce中获取WC_Cart对象中的特定值?

嘿,我来帮你搞定从WC_Cart对象里提取特定值的事儿!WooCommerce其实给咱们准备了不少官方API方法,比直接硬怼对象内部属性靠谱多了——毕竟直接操作内部属性可能会因为WooCommerce版本更新出问题。下面分两种情况给你唠唠:

一、优先用WooCommerce官方提供的方法

这是最稳妥的方式,官方方法会考虑兼容性,就算后续版本迭代也不容易出bug。举几个常用场景的例子:

  • 获取购物车不含税的总金额:
    $subtotal = WC()->cart->get_subtotal();
    
  • 获取购物车含税的最终总金额:
    $total = WC()->cart->get_total();
    
  • 获取购物车里的商品总数量(所有商品数量相加):
    $item_count = WC()->cart->get_cart_contents_count();
    
  • 遍历购物车中的单个商品,提取商品ID、数量、价格等信息:
    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        // 获取商品ID
        $product_id = $cart_item['product_id'];
        // 获取商品数量
        $quantity = $cart_item['quantity'];
        // 获取商品对象(可以调用更多产品方法)
        $product = $cart_item['data'];
        $product_name = $product->get_name(); // 获取商品名称
        $product_price = $product->get_price(); // 获取商品单价
    }
    
二、直接访问对象内部属性(不推荐,但应急可用)

如果你确实需要直接获取你提到的cart_contents这类内部属性,也可以这么做,但要注意:WooCommerce随时可能调整内部结构,这种方式兼容性差,尽量少用。比如:

  • 获取购物车所有商品的原始数组:
    $cart_contents = WC()->cart->cart_contents;
    
  • 从数组里提取第一个商品的product_id:
    if (!empty($cart_contents)) {
        $first_item_key = array_key_first($cart_contents);
        $first_product_id = $cart_contents[$first_item_key]['product_id'];
    }
    
  • 提取某个商品的line_subtotal(商品小计):
    foreach ($cart_contents as $item) {
        $line_subtotal = $item['line_subtotal'];
        // 或者获取含税小计
        $line_subtotal_tax = $item['line_subtotal'] + array_sum($item['line_tax_data']['subtotal']);
    }
    

最后提醒一句:能官方方法解决的,就别直接碰内部属性,省心又安全!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:55:46