At most 10 of each product per order
Customers can buy at most 10 of any product in one order. The quantity box stops at 10 and the cart explains the limit.
Before you switch it on: Set your limit in $snipfire_max and translate the message.
It arrives switched off, even when you install its whole pack with "Switch on after installing".
<?php
$snipfire_max = 10;
add_filter(
'woocommerce_quantity_input_max',
static function ( $max ) use ( $snipfire_max ) {
return ( $max > 0 && $max < $snipfire_max ) ? $max : $snipfire_max;
}
);
add_filter(
'woocommerce_add_to_cart_validation',
static function ( $passed, $product_id, $quantity, $variation_id = 0 ) use ( $snipfire_max ) {
$id = $variation_id ? $variation_id : $product_id;
foreach ( WC()->cart ? WC()->cart->get_cart() : array() as $item ) {
if ( (int) ( $item['variation_id'] ? $item['variation_id'] : $item['product_id'] ) === (int) $id ) {
$quantity += $item['quantity'];
}
}
if ( $quantity > $snipfire_max ) {
wc_add_notice( sprintf( 'You can buy at most %d of this product per order.', $snipfire_max ), 'error' );
return false;
}
return $passed;
},
10,
4
);
add_filter(
'woocommerce_update_cart_validation',
static function ( $passed, $key, $values, $quantity ) use ( $snipfire_max ) {
if ( $quantity > $snipfire_max ) {
wc_add_notice( sprintf( 'You can buy at most %d of this product per order.', $snipfire_max ), 'error' );
return false;
}
return $passed;
},
10,
4
);
Good to know
Change $snipfire_max and translate the message. Works for the classic cart; the block cart uses the quantity limit shown in the box.
In these packs
- WooCommerce: cart and checkout: Free-shipping progress, coupon links, quantity limits and a cleaner checkout.