I need to display a message to a customer when the quantity exceeds a certain calculation. I would like to make this fail validation and post a message. I can do so with add to cart validation, but I can never get a message to display in woocommerce blocks when putting a notice in, what is the proper way to do this?
The first function works great, but works on page load.
The second does nothing, but would need to run on AJAX
add_action('woocommerce_add_to_cart_validation', 'gb_wc_woocommerce_add_to_cart_validation', 10, 6);
function gb_wc_woocommerce_add_to_cart_validation($passed, $product_id, $quantity, $variation_id = 0, $variations = null, $cart_item_data = null) {
//TODO check if this causes a cart stock fail, if so return false to prevent adding to cart
wc_add_notice(sprintf(__('Returning true to allow this add to cart operation. Product:Variation ID passed is: %s:%s with quantity of: %s', 'woocommerce'), $product_id, $variation_id, $quantity), 'error');
return true;
}
add_action('woocommerce_update_cart_validation', 'my_woocommerce_check_cart_items', 10, 0);
function my_woocommerce_check_cart_items_test() {
wc_add_notice( sprintf( __( 'This is an update cart fail notice which never appears on the front end.', 'woocommerce' ), $_product->get_name() ), 'error' );
return false;
}
source: https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.697