Limit how many of each product a customer can buy, and require a minimum, with checks on the product page and in the cart.
const NAHNU_MIN_QTY = 1;
const NAHNU_MAX_QTY = 5;
// Limit the quantity box on product pages.
add_filter( 'woocommerce_quantity_input_args', function ( array $args, $product ): array {
$args['min_value'] = NAHNU_MIN_QTY;
$args['max_value'] = $product->get_max_purchase_quantity() > 0 ? min( NAHNU_MAX_QTY, $product->get_max_purchase_quantity() ) : NAHNU_MAX_QTY;
return $args;
}, 10, 2 );
// Check every line in the cart (works for classic and block checkout).
add_action( 'woocommerce_check_cart_items', function (): void {
foreach ( WC()->cart->get_cart() as $item ) {
$qty = (int) $item['quantity'];
$name = $item['data']->get_name();
if ( $qty > NAHNU_MAX_QTY ) {
wc_add_notice( sprintf( 'You can buy up to %d of "%s" per order.', NAHNU_MAX_QTY, $name ), 'error' );
} elseif ( $qty < NAHNU_MIN_QTY ) {
wc_add_notice( sprintf( 'Please buy at least %d of "%s".', NAHNU_MIN_QTY, $name ), 'error' );
}
}
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Limited releases, wholesale minimums and fair-use limits all need quantity rules. This snippet sets a minimum and maximum quantity for every product.
The woocommerce_quantity_input_args filter changes the limits on the quantity box, so customers can’t pick more than the maximum on the product page. If a product has less stock than your maximum, the stock limit wins.
The quantity box is only a convenience; people can still change quantities in the cart. The real check runs on woocommerce_check_cart_items, which WooCommerce runs for the cart page, the classic checkout and the block-based Cart and Checkout. If a line breaks a rule, the customer sees an error and can’t place the order until they fix it.
$item['product_id'] or a product category inside the loop.Set the maximum to 2, add 3 of a product to the cart and go to checkout. You should see the error and be unable to pay until you lower the quantity.