• Resolved danielbmxd

    (@danielbmxd)


    Hello, is there a hook or filter that automatically removes products out of stock from the cart? In the case of a customer who enters after time and some products are no longer available and avoid having to delete them manually

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Support abwaita a11n

    (@abwaita)

    Hi @danielbmxd,

    I found the following custom code from this article and it seems to be working well:


    Link to image: https://snipboard.io/DgH2IY.jpg

    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 out of stock.", 'woocommerce' ), $product_name);
     
                wc_add_notice( $msg, 'error' );
            }
        }
     
    }
     
    add_action('woocommerce_before_cart', 'orb_check_for_out_of_stock_products');

    * I recommend using Code Snippets to add custom code to your site.

    Let us know how it goes.
    Thanks.

    HI @danielbmxd

    We’ve not heard back from you in a while, so I’m marking this thread as resolved. Hopefully, the above suggestion was helpful. If you have further questions, please feel free to open a new topic.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Remove items’ is closed to new replies.