In WooCommerce, each product is assigned a unique identifier known as the ‘Product ID.’ These IDs are typically system-generated and differ from SKU which are user-friendly names set by store owners. Although product SKU serve a similar purpose in inventory management, they cannot be used in cases of site-wide changes to products.
When store owners need to remove specific products from their carts, using Product IDs is a practical and reliable approach. Reasons for removing products from the cart may include limited-time offer expirations, the conclusion of seasonal sales, or item unavailability.
This post helps you to remove a product from the WooCommerce cart programmatically.
Where to Add Custom Code in WooCommerce?
It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.
Preliminary Steps
Choose the product and its corresponding ID for which you intend to remove it from the cart as soon as this specific product is added to the cart. The Product ID can be found from the products section of your dashboard. If you hover the mouse over a product, you will be able to find the ID, as shown in the image provided below.
In this case, I have selected the product ‘Sony 32 Inch LED Television’ and its ID is 1404.
Use case 1: Remove a Product from the Cart Using the Product ID in WooCommerce
Imagine you run an online store where you offer discounts on specific products only on weekends. So, once the discount offer timeframe ends, and if any customer tries to purchase the products they added to their cart during the offer period, the provided code snippet helps in such a scenario. The below code snippet implements a feature where a specific product such as ‘LED Television’ with the product ID ‘1404’ is automatically removed from the customer’s shopping cart when added to the cart.
add_action( 'template_redirect', 'ts_remove_product_from_cart_programmatically' ); function ts_remove_product_from_cart_programmatically() { if ( is_admin() ) return; $product_id = 1404; // Change it to the desired product ID $product_cart_id = WC()->cart->generate_cart_id( $product_id ); $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id ); if ( $cart_item_key ) { WC()->cart->remove_cart_item( $cart_item_key ); // Add a notice message wc_add_notice( 'Product with ID ' . $product_id . ' has been removed from the cart.', 'notice' ); } }
Output
Use case: Product removed from the cart
If a customer adds the product with the ID 1404 to their cart, the product will be automatically removed from the cart.
The below image shows that the product added has been removed and thus displays the notice message.
Code Explanation
- Hook Registration:
- The code starts by registering an action hook using add_action.
- The template_redirect hook is used, which fires when WordPress is ready to handle template loading and content display.
- Conditional Check:
- The code checks if the current page is within the WordPress admin dashboard by using is_admin().
- If the code is being executed in the admin area (e.g., when managing the website from the WordPress backend), it halts further execution to prevent unintended actions.
- Select Product to Remove:
- The code identifies the product to be removed from the cart. In this case, it’s represented by a product ID: $product_id = 1487.
- This product ID can be customized to target any specific product in the WooCommerce store.
- Generate a Unique Cart Identifier:
- To work with the cart item, the code generates a unique identifier known as the cart ID for the selected product.
- WooCommerce provides the generate_cart_id method for this purpose. The result is stored in the $product_cart_id variable.
- Find the Product in the Cart:
- The code searches the cart to locate the product with the previously generated cart ID.
- The find_product_in_cart method is used for this task, and the result is stored in $cart_item_key.
- If a matching cart item is found, it indicates that the product is already in the cart.
- Remove the Product from the Cart:
- The code employs a conditional statement to check whether a valid $cart_item_key (i.e., a matching cart item) exists.
- If a match is found (meaning the product is in the cart), the code utilizes the remove_cart_item method to remove the specified product from the WooCommerce shopping cart.
Use case 2: Remove a Product from the Cart Based on Product Category
The following code snippet is beneficial for store owners aiming to remove all products from a particular category. Within the code snippet, I’ve used the ‘Kitchen Appliances’ slug. So, when a customer adds any product from the ‘Kitchen Appliances’ category, the code checks the conditions and proceeds to remove those items from the cart automatically.
add_action('woocommerce_before_calculate_totals', 'ts_remove_products_by_category'); function ts_remove_products_by_category($cart) { // Define the category slug to target $category_to_remove = 'Kitchen Appliances'; // Change to the desired category slug foreach ($cart->get_cart() as $cart_item_key => $cart_item) { $product = $cart_item['data']; if (has_term($category_to_remove, 'product_cat', $product->get_id())) { $cart->remove_cart_item($cart_item_key); } } }
Output
Use case: Product categories of ‘Kitchen Appliances’ removed from cart
Let’s consider that a customer has added a mixed kind of products such as a Smartwatch from the electronics category and a Kettle from the kitchen appliances category.
Now, let’s go ahead and check the cart. You will find the products belonging to the kitchen appliances category to be removed and the cart will be left with other category items only.
Recommended Reading: How to Show WooCommerce Related Products on the Cart Page? |
- Hook into ‘woocommerce_before_calculate_totals’: This code begins by using the add_action function to hook into the woocommerce_before_calculate_totals action. This action is triggered just before WooCommerce calculates the cart totals.
- Remove Products by Category: Inside the hooked function ‘remove_products_by_category,’ the code defines a category slug to target, which is ‘Kitchen Appliances’ in this example. It then iterates through the cart items, checks if a product belongs to the specified category using has_term, and if so, removes the product from the cart using $cart->remove_cart_item($cart_item_key).
Conclusion
The above code snippets aim to remove a specific product from the shopping cart based on product ID and product categories. Removing products from the cart programatically comes in handy when you are automatically adding a product to your WooCommerce cart.
Let us know how the code was useful or any other queries in the comments section.