Automatically removes any cart items that went out of stock after being added. Instead of showing an error at checkout, this snippet silently clears the unavailable product and shows a notice, preventing failed orders and a frustrating customer experience.
add_action( 'woocommerce_check_cart_items', function() {
if ( ! WC()->cart ) {
return;
}
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( ! $product->is_in_stock() ) {
WC()->cart->remove_cart_item( $cart_item_key );
wc_add_notice(
sprintf(
/* translators: %s: product name */
__( '"%s" has been removed from your cart as it is no longer available.', 'woocommerce' ),
esc_html( $product->get_name() )
),
'notice'
);
}
}
} );