Starting in WooCommerce 11.2, the Store API has a filter for rejecting a cart item quantity change error: woocommerce_store_api_cart_item_quantity_validation. The legacy cart had this via woocommerce_update_cart_validation; the Store API, and with it the Cart and Checkout blocks, had no equivalent.
The filter was added in PR #67928, in response to issue #52263.
The details
The filter runs after the core min, max, and multiple-of checks, when a cart item quantity is updated or a product already in the cart is added again. It does not run on the first add of a product; use the woocommerce_store_api_validate_add_to_cart action for that.
apply_filters( 'woocommerce_store_api_cart_item_quantity_validation', true, $quantity, $product, $cart_item );Return a WP_Error to reject the quantity; the Store API sends its code and message in a 400 response and the block UI shows the message to the shopper. Any other return value is ignored and the quantity is accepted, including false. Notices added with wc_add_notice() are not read.
Example: cap a product at 3 per order
add_filter( 'woocommerce_store_api_cart_item_quantity_validation', function ( $valid, $quantity, $product, $cart_item ) {
if ( $quantity > 3 ) {
return new \WP_Error(
'invalid_custom_condition',
sprintf( 'Only 3 of "%s" are allowed per order.', $product->get_name() )
);
}
return $valid;
}, 10, 4 );The legacy pattern of wc_add_notice() plus return false does not carry over. A callback copied from woocommerce_update_cart_validation as is will accept every change.
Backward compatibility
- The filter is additive; with no callbacks attached, the Store API behaves as before.
- It can add rejections but never loosen the declared min, max, or multiple-of limits. Numeric bounds belong in the
woocommerce_store_api_product_quantity_*filters. woocommerce_update_cart_validationis unchanged and still only runs for the shortcode cart.
How can I tell if this affects me?
Search your extension for woocommerce_update_cart_validation. If you use it to reject quantity changes, that rule only applies to the shortcode cart; the Cart block and any Store API client bypass it.
What action should I take?
- Add a callback on
woocommerce_store_api_cart_item_quantity_validationand return aWP_Errorfor the quantities you reject. - Keep your
woocommerce_update_cart_validationcallback for the shortcode cart; the two filters cover different carts. - Test with the Cart block: change the quantity of an item past your rule and check the error appears.
Leave a Reply