In this simple guide I will show how to check in WooCommerce if a product with specific ID is in cart programmatically. We are also going to do it for different types of products and take a look at products with custom cart item data.
Usually when I work with any WordPress or WooCommerce projects, if I face with something new during the development process, I usually try to share what I learnt immediately on my blog, here. But not always I did that. In 2014 I began my work with the awesome and super complicated project with WooCommerce, WooCommerce Memberships and WooCommerce Subscriptions. Let me share with you a piece of that work.
In this tutorial I am going to show you a different ways of adding a product to WooCommerce cart via code.
And by the way, if you were looking how to add product to an order, you need a completely different tutorial – here it is.
In this tutorial we are going to remove the “Update cart” button in WooCommerce and to do auto-update cart when quantity changes.
Below on the screenshot you can see how it is going to look like:
Let’s skip the introduction part and get straight to the solution. There are actually two ways depending on what you are going to achieve:
WC()->cart->get_cart_contents_count()– it allows to get a number of cart items including their quantity counts. For example, if you have 10 snowboards and 1 avocado toast in the cart, this method will return
11! You can see it yourself if you open this method in WooCommerce source code. It just gets the whole cart array from
WC()->cart->get_cart()and then for each item it gets its quantity parameter.
count( WC()->cart->get_cart() )– this implementation actually returns the number of unique products in the cart, one per product.
In this tutorial I will show you how we can override prices of the products that are already in the Cart with the help of
woocommerce_before_calculate_totals action hook and cart object.
Here we are going to deal with products that have already been added to cart, if you would like to add products to the cart with a custom price, I can recommend you this example.
Below we are going to set the same price ($10) for every product in the cart programmatically.