How to validate complete cart and prevent line item is updated in WooCommerce

Viewed 1442

I am using woocommerce_update_cart_action_cart_updated for complete cart validation. The cart still gets updated even after $cart_updated is made false.

Is this the proper usage of this filter or I am doing something wrong?

I dont want to use woocommerce_update_cart_validation as it validates item by item in cart rather than the complete cart as a whole

function filter_woocommerce_update_cart_action_cart_updated( $cart_updated ) {
    global $woocommerce;
    $cart_items = $woocommerce->cart->get_cart();   
    //iterate thru all cart items
    foreach($cart_items as $cart_item) {
        $Availability=check_availability();
        if('PAST_NA'==$Availability) {
            $cart_updated = false;
            wc_add_notice( 'Items not available for the selected dates', 'error' );
            return $cart_updated;

        }
        elseif('CART_NA'==$Availability) {
            $cart_updated = false;
            wc_add_notice('Your cart has more than available items for the selected dates', 'error' );
            return $cart_updated;
        }
        else{
            $cart_updated=true;
        }

    }
     return $cart_updated;
}
add_filter( 'woocommerce_update_cart_action_cart_updated', 'filter_woocommerce_update_cart_action_cart_updated', 10, 1 );
1 Answers

As you can see here. First you have the validation hook per item (woocommerce_update_cart_validation), on line 670 ($passed_validation) is true, so the item is already passed and updated and woocommerce_update_cart_action_cart_updated is to late for validation.

Proof of concept

function filter_woocommerce_update_cart_action_cart_updated( $cart_updated ) {
    $cart_updated = false;

    if ( $cart_updated == false ) {
        wc_add_notice( __( 'my error', 'woocommerce' ), 'error' );
    }

    return $cart_updated;
}
add_filter( 'woocommerce_update_cart_action_cart_updated', 'filter_woocommerce_update_cart_action_cart_updated', 10, 1 );

EDIT:

Maybe you can still use woocommerce_update_cart_action_cart_updated where you will adjust the updated item again with WC()->cart->set_quantity( $cart_item_key, $quantity );.

As far as I know there is no hook that prevents updating per item and in the meantime applies a check to the entire shopping cart

Related