I wanted to restrict WooCommerce to only selling in set quantities of 4, 8, or 12 and on. I wrote a code, which will show a quantity error on the cart page or while processing checkout. While processing checkout, it will work exactly like checkout field validation.
The code snippet below will allow the user only to purchase set a minimum quantity 4 on in multiples of 4.
Code 1: Show quantity error while checkout
/**
* @snippet WooCommerce: Show quantity error while checkout
* @author Sandesh Jangam
* @donate $7 https://www.paypal.me/SandeshJangam/7
*/
add_action( 'woocommerce_checkout_process', 'ts_minimum_order_item_count' );
function ts_minimum_order_item_count() {
$multiples = 4;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 ) {
wc_add_notice( sprintf( __( 'Items can only be purchased in multiples of %s.', 'woocommerce'), $multiples ), 'error' );
}
}
Code 2: Show quantity error on the cart page
When the user visits the cart page and quantity is not in multiples of 4, then it will show notice.
/**
* @snippet WooCommerce: Show quantity error on the cart page
* @author Sandesh Jangam
* @donate $7 https://www.paypal.me/SandeshJangam/7
*/
add_action( 'woocommerce_check_cart_items', 'ts_check_cart_quantities' );
function ts_check_cart_quantities() {
if( ! is_cart() ) {
return;
}
$multiples = 4;
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$total_products += $values['quantity'];
}
if ( ( $total_products % $multiples ) > 0 ) {
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), $multiples ), 'error' );
}
}
2 thoughts on “WooCommerce: Quantity in Multiples of X on Cart and Before Checkout”
Hi Sandesh,
Thanks for your snippet, it works great!
I’m trying to apply this rule only on one category of product.
How can I add this filter in the code?
Thanks for your help
Hi Sandesh,
is there a way to exclude one specific category from your rule of quantity of 4?
Like for other product categories, where you don’t want this rule to apply?
Thanks Tanja