In WooCommerce, I aim to enforce a minimum quantity restriction on purchased items by category.
Here's an example:
- For products 1, 2, and 3 (all in the Shoes category), the combined minimum quantity is 10.
- For products 4, 5, and 6 (all in the Pants category), the combined minimum quantity is 10.
- For products 7, 8, and 9 (all in the Shirt category), the combined minimum quantity is 10.
Each category should have at least 10 products ordered. However, these can be spread across multiple products within the same category.
I found a piece of code that partially meets my needs. It displays the minimum notice, but it allows mixing of multiple categories, which is not what I want. Here's the code:
add_action('woocommerce_check_cart_items', 'custom_set_min_total');
function custom_set_min_total()
{
if (is_cart() || is_checkout()) {
global $woocommerce, $product;
$i = 0;
foreach ($woocommerce->cart->cart_contents as $product) :
$minimum_cart_product_total = 10;
if (has_term( array('oneya', 'twoya'), 'product_cat', $product['product_id'])) :
$total_quantity += $product['quantity'];
endif;
endforeach;
foreach ($woocommerce->cart->cart_contents as $product) :
if (has_term( array('oneya', 'twoya'), 'product_cat', $product['product_id'])) :
if ($total_quantity < $minimum_cart_product_total && $i == 0) {
wc_add_notice(
sprintf(
'A minimum of 10 products is required per unique design. You have not met these requirements. Please add at least 10 items to proceed with your order.',
$minimum_cart_product_total,
$total_quantity
),
'error'
);
}
$i++;
endif;
endforeach;
}
}
To restrict items to a minimum combined quantity (10) per category, try the following:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.