How To Get All Items In A WooCommerce Cart Using PHP
It’s pretty easy to grab all product data from the WooCommerce cart.
For simplicity, we will only really deal with product data in this tutorial.
You can obviously grab details about the user’s cart, but the purpose of this is to deal with product data.
// Get full cart object
$items = WC()->cart->get_cart();
// Loop through cart items
foreach( $items as $item => $values ) {
// Load product object
$product = wc_get_product( $values['data']->get_id() );
// Access product data using product object
$product_title = $product->get_title();
// Get product qty in cart just in case
$quantity_in_cart = $values['quantity'];
// Do what you need to do...
}
The above code block is pretty much all you need, it’s really simple.
Once you have the $product object you can access any product data that you could imagine.
If you’re not sure how or what you can access through the product object, you can read our how to guide on getting all product info in woocommerce.
Thanks, clear and straight peace of code on how to get the items from the cart. I needed that in order to get the cart products Ids, using product->get_id() method.
Beautiful 🙂
hello guys How are you
Fantastic, thankyou for asking
Hi this code only gets a one item from the cart. How can I get all items?
Hi Sam,
Thanks for reading our article.
It does pull all items from the cart and runs them through a foreach loop.
The following line:
Runs every time it finds a product, so for every product in the cart you will perform whatever action you are trying to.
If you need a hand putting something together let me know and I will assist with it.
Thanks, Chris