I want the number of products in the customer cart to be a multiple of 6 or 12 or 4. I found this code for multiplier 6 in the forum, but it needs to be edited for other coefficients.
Based on Set item quantity to multiples of “x” for products in a specific category in Woocommerce code thread:
// check that cart items quantities totals are in multiples of 6
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities' );
function woocommerce_check_cart_quantities() {
$multiples = 6;
$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' );
}
Based on Woocommerce Order Quantity in Multiples answer code:
// Limit cart items with a certain shipping class to be purchased in multiple only
add_action( 'woocommerce_check_cart_items', 'woocommerce_check_cart_quantities_for_class' );
function woocommerce_check_cart_quantities_for_class() {
$multiples = 6;
$class = 'bottle';
$total_products = 0;
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = get_product( $values['product_id'] );
if ( $product->get_shipping_class() == $class ) {
$total_products += $values['quantity'];
}
}
if ( ( $total_products % $multiples ) > 0 )
wc_add_notice( sprintf( __('You need to purchase bottles in quantities of %s', 'woocommerce'), $multiples ), 'error' );
}
How to handle multiples of 6 or 12 or 4 instead of just one?
As 12 is already a multiple of 4 or 6, you need only to check for items multiples of 4 or 6 using the following code (commented):
add_action( 'woocommerce_check_cart_items', 'check_cart_items_quantities_conditionally' );
function check_cart_items_quantities_conditionally() {
$multiples = array(4, 6); // Your defined multiples in an array
$items_count = WC()->cart->get_cart_contents_count(); // Get total items cumulated quantity
$is_multiple = false; // initializing
// Loop through defined multiples
foreach ( $multiples as $multiple ) {
if ( ( $items_count % $multiple ) == 0 ) {
$is_multiple = true; // When a multiple is found, flag it as true
break; // Stop the loop
}
}
// If total items cumulated quantity doesn't match with any multiple
if ( ! $is_multiple ) {
// Display a notice avoiding checkout
wc_add_notice( sprintf( __('You need to buy in quantities of %s products', 'woocommerce'), implode(' or ', $multiples) ), 'error' );
}
}