Sometimes your users may add products to their shopping cart and then come back to it later. They could have been interrupted for various reasons. In the meantime, however, one or more of the added products could become out of stock.

WooCommerce does a good job informing the user that some products are out of stock and asks the user to remove them from the cart.

woocommerce warning on out of stock products in wc cart

If the products in the cart are way too many it would be pretty annoying for the user to have to click on every single out of stock product so it's removed from the cart.

With the help of this code snippet the out of stock products will be removed from the cart automatically and the user will be shown a message which product(s) have been removed.


woocommerce warning on out of stock products removed from WC

Here's a video demo of the snippet in action



 * This snippet allows you automatically remove any out of stock items when the user views their shopping cart.
 * This would be in cases when users add products to their cart and come back it it later.
 * You can install this snippet in your functions.php
 * or
 * even better in as an mu-plugin in mu-plugins/orb_check_for_out_of_stock_products.php
 * Blog post:
 * @copyright Slavi Marinov |
function orb_check_for_out_of_stock_products() {
	if ( WC()->cart->is_empty() ) {

	$removed_products = [];

	foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
		$product_obj = $cart_item['data'];

		if ( ! $product_obj->is_in_stock() ) {
			WC()->cart->remove_cart_item( $cart_item_key );
			$removed_products[] = $product_obj;

	if (!empty($removed_products)) {
		wc_clear_notices(); // remove any WC notice about sorry about out of stock products to be removed from cart.

		foreach ( $removed_products as $idx => $product_obj ) {
			$product_name = $product_obj->get_title();
			$msg = sprintf( __( "The product '%s' was removed from your cart because it is out of stock.", 'woocommerce' ), $product_name);

			wc_add_notice( $msg, 'error' );


add_action('woocommerce_before_cart', 'orb_check_for_out_of_stock_products');

You can add this code to your functions.php of your (child) theme or even better in as an mu-plugin (or system plugin) in mu-plugins/orb_check_for_out_of_stock_products.php

Note: If you're adding the code to your functions php file you will have to omit the starting <?php tag because functions.php already has one.


Do you need any of the code in this post customized or packaged into a plugin? Get a free quote
Referral Note: When you purchase through an referral link (if any) on our site, we earn a commission.