WooCommerce PHP Intermediate Requires WooCommerce

Set a Minimum and Maximum Quantity Per Product

Limit how many of each product a customer can buy, and require a minimum, with checks on the product page and in the cart.

Tested on WordPress 7.1 PHP 8.3 Updated
functions.php 22 lines
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' );
		}
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • The limits apply to every product. To limit only some, check $item['product_id'] or a product category inside the loop.
  • Customers can still place separate orders. For strict “one per customer” rules you need to check past orders too.

How to test it

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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only