dongxueji2838 2017-10-28 03:43
浏览 213
已采纳

在Woocommerce中按项目ID获取购物车项目数量

In WooCommerce, I have created a mini cart and I want the get the item quantity available in the current cart.

As i have tried this:

  $items = $woocommerce->cart->get_cart();

      foreach($items as $item => $values) {
          $product_id = $values['product_id'];
          if ( $product_id == $id ){
            $product_qnty = $values['quantity'];
          }
          break;
      }

Is there any single function to get the cart item quantity by cart item ?

  • 写回答

1条回答 默认 最新

  • dongqie5529 2017-10-28 13:05
    关注

    May be you should look first in the woocommerce template code cart/mini-cart.php where you will find the official related code.

    Note: The "item ID" is only available in WC_Orders items loop, but not in WC_Cart which is a "Cart item Key". So you are surely talking about the product ID. But if you look to the code of the official template cart/mini_cart you will need to use the WC_Product object instead of the $product_id

    So you can always build a custom function like (with a $product argument, the WC_Product object) that you can use in the corresponding template code or in your custom code:

    function get_item_qty( $product ){
        foreach( WC()->cart->get_cart() as $cart_item )
            // for variable products (product varations)
            $product_id = $product->get_parent_id();
            if( $product_id == 0 || empty( $product_id ) )
                $product_id = $product->get_id();
    
            if ( $product_id == $cart_item['product_id'] ){
                return $cart_item['quantity'];
                // break;
            }
        return;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


    USAGE (example): Here we will output the quantity of the $product (WC_Product object):

    // Output the quantity based on the $product object
    echo __('Quantity'). ': ' . get_item_qty( $product );
    

    Official Documentation: Template Structure + Overriding Templates via a Theme

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序