Get the cart item quantity by item id in Woocommerce

Ranjit picture Ranjit · Oct 28, 2017 · Viewed 9.6k times · Source

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 ?

Answer

LoicTheAztec picture LoicTheAztec · Oct 28, 2017

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