简体   繁体   English

在Woocommerce中按商品ID获取购物车商品数量

[英]Get the cart item quantity by item id in Woocommerce

In WooCommerce, I have created a mini cart and I want the get the item quantity available in the current cart. 在WooCommerce中,我创建了一个迷你购物车,我希望获取当前购物车中可用的商品数量。

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 ? 是否有单个功能可以按购物车项目获取购物车数量?

May be you should look first in the woocommerce template code cart/mini-cart.php where you will find the official related code. 也许您应该首先在woocommerce模板代码cart / mini-cart.php中查找,在那里您可以找到官方的相关代码。

Note: The "item ID" is only available in WC_Orders items loop, but not in WC_Cart which is a "Cart item Key". 注意:“商品ID”仅在WC_Orders商品循环中可用,而在WC_Cart(“购物车钥匙”)中不可用。 So you are surely talking about the product ID. 因此,您肯定在谈论产品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 但是,如果您查看官方模板cart / mini_cart的代码,则将需要使用WC_Product对象而不是$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: 因此,您始终可以构建一个自定义函数,例如(带有$product参数,WC_Product对象) ,可以在相应的模板代码或自定义代码中使用:

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. 代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。


USAGE (example) : Here we will output the quantity of the $product ( WC_Product object) : USAGE (示例) :在这里,我们将输出$product的数量WC_Product对象)

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

Official Documentation: Template Structure + Overriding Templates via a Theme 官方文档: 模板结构+通过主题覆盖模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM