Auto remove out of stock items in cart then notify account user – Woocommerce

function orb_check_for_out_of_stock_products() {
if ( WC()->cart->is_empty() ) {
    return;
}

$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 now out of stock. Sorry for any inconvenience caused.", 'woocommerce' ), $product_name);

        wc_add_notice( $msg, 'error' );
    }
}

}
add_action('woocommerce_before_cart', 'orb_check_for_out_of_stock_products');

 

In case of any complain or © copyright or issues please check disclaimer page for faster resolutions.