Get the cart item quantity by item id in Woocommerce
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
Ranjit
Hi I am a dynamic coder having 9 years of experinces. I do designing, developing, deploying It & Mobile Apps for start-ups & established businesses. Since my incorporation in the year 2011, I am focused on IT consulting by providing services such as development and maintenance to new/existing application. I work with It technologies such as PHP/CakePHP/Laravel, JQuery, Ajax HTML5 and Wordpress Commitment I never just do a task for sake of it but with lots of love & passion. With full self-confidence, I never stop until the goal is reached! Best in Wordpress There is no denying that WordPress has become the most popular CMS solution of choice. From its humble beginnings as a simple blogging solution, today, WordPress is an enterprise grade Content Management Solution. I have a vast knowledge and experience of WordPress and no matter if you need a simple marketing website, or a completely custom built site with specialised functionality and eCommerce capabilities, our team can make it happen. Thank you
Updated on June 04, 2022Comments
-
Ranjit almost 2 years
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 ?