Learn how to automatically remove out-of-stock products from the WooCommerce cart and clear the cart when users leave your site.
Add Custom Code to Your Theme’s functions.php or If your site is a wordpress site you can use the Code Snippet plugin.
1. Go to WordPress Dashboard
2. Add new plugins
3. Search Code Snippet Plugin
4. Install and activate the Code snippet plugin
5. Add New Code, Select Function.php, and Past the below code.
This is the Code to Remove Woocommerce Out-of-Stock Products Automatically:
add_action('woocommerce_cart_loaded_from_session', 'remove_out_of_stock_items_session', 20);
function remove_out_of_stock_items_session() {
$cart = WC()->cart;
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product = wc_get_product($cart_item['product_id']);
if (!$product->is_in_stock()) {
$cart->remove_cart_item($cart_item_key);
}
}
}
Final Testing & Troubleshooting
-
Test the Out-of-Stock Removal:
- Add a product to the cart.
- Mark it as out of stock in WooCommerce.
- Refresh the cart page—the product should disappear automatically.
(CTA)
Did this guide help you? Let me know in the comments!
Need help? Contact me for WooCommerce customization services!
asad
25 February 2025Owo Great! Its really working. Thank you so much.