How to set minimum and maximum purchasable quantity for a WooCommerce product without any plugin.

One of the best things about WooCommerce which makes it so widely adapted e-commerce platform is it’s customizability.

With this little peice of code we can limit the minumun purchasable quantity for all products in the site

<?php 
/**
 * Show error if quantity is less than 2.
 */
function pram_minimum_item_quantity_validation( $passed, $product_id, $quantity, $variation_id = 0, $variations = false ) {

	$minimum = 2;

	if ( $quantity < $minimum ) {
		wc_add_notice( sprintf( 'Minumum purchasable quantity for this product is "%d"', $minimum ), 'error' );
        return false;
	}
}
add_action( 'woocommerce_add_to_cart_validation', 'pram_minimum_item_quantity_validation', 1, 5 );

If you want to add this restriction for only a certain product then you only need to make a slight modification:

<?php 

/**
 * Show error if quantity is less than 2 and only for a certain product.
 */
function pram_minimum_item_quantity_validation( $passed, $product_id, $quantity, $variation_id = 0, $variations = false ) {

	$minimum = 2;

	if ( 52 === $product_id && $quantity < $minimum ) {
		wc_add_notice( sprintf( 'Minumum purchasable quantity for this product is "%d"', $minimum ), 'error' );
        return false;
	}

	return $passed;
}
add_action( 'woocommerce_add_to_cart_validation', 'pram_minimum_item_quantity_validation', 1, 5 );

Set maximum purchasable quantity

<?php 
/**
 * Show error if quantity is more than 2.
 */
function pram_minimum_item_quantity_validation( $passed, $product_id, $quantity, $variation_id = 0, $variations = false ) {

	$maximum = 2;

	if ( $quantity > $maximum ) {
		wc_add_notice( sprintf( 'Maximum purchasable quantity for this product is "%d"', $maximum ), 'error' );
		return false;
	}

	return $passed;
}
add_action( 'woocommerce_add_to_cart_validation', 'pram_minimum_item_quantity_validation', 1, 5 );

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up Next:

Basic Rate-limiting in WooCommerce with native class

Basic Rate-limiting in WooCommerce with native class