I’M Programmer & Full-Stack Web Developer from Bangladesh.I am an expert at creating websites and designing them to look professional. I particularly specialize in using WordPress. I can make a website for your business, portfolio, company, online store, or blog. I can create a special, neat and cool picture design for you to use.

Contacts

Dhaka, Bangladesh

krumman050@gmail.com

+8801634279297

+8801829077024

Development Technology wordpress
Automatically Remove Out-of-Stock Items from WooCommerce Cart

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

  1. 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!

Author

Rumman Khan

Comment (1)

  1. asad
    25 February 2025

    Owo Great! Its really working. Thank you so much.

Leave a comment

Your email address will not be published. Required fields are marked *