In WooCommerce, I need to set up a minimum quantity for each item of a product category. I searched the forum and found some code that works fine except it only counts the Quantity for a product category in total:
add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );
add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );
function wc_minimum_order_amount() {
$minimum = 5; //Qty product
if ( WC()->cart->cart_contents_count < $minimum ) {
$draught_links = array();
foreach(WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_cat' );
foreach ($terms as $term) {
$draught_links[] = $term->name;
}
}
if (in_array("Noten", $draught_links)){
$on_draught = true;
}else{
$on_draught = false;
}
if( is_cart() ) {
if($on_draught){
wc_print_notice(
sprintf( 'Bitte beachte die Mindestbestellmenge. Du brauchst mindestens %s Notenexemplare pro Arrangement. Aktuell hast du %s Stück in deinem Warenkorb.' ,
$minimum ,
WC()->cart->cart_contents_count
), 'error'
);
}
} else {
if($on_draught){
wc_add_notice(
sprintf( 'Bitte beachte die Mindestbestellmenge. Du brauchst mindestens %s Notenexemplare pro Arrangement. Aktuell hast du %s Stück in deinem Warenkorb.' ,
$minimum ,
WC()->cart->cart_contents_count
), 'error'
);
}
}
}
}
For example if I have two products (A and B) of belonging to the same product category and set up minimum quantity for this category to 5, the error message for the customer won't appear in this case:
- Product A: 3
- Product B: 2
I need a min quantity of 5 for every single product of that category.
Do you have an idea how to change and optimize the following code?
Since WooCommerce 3, your actual code is outdated and not convenient… There is multiple ways:
1) The best way: Set up the minimum quantity at product level (for a product category):
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
2) Alternative way: Checking cart items and displaying an error message (similar to your code):
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
To make it work for parent product category too, you will also add this custom function:
Code goes in functions.php file of your active child theme (or active theme). Tested and work.
Then in the existing code, you will replace:
by
That will allow you to handle parent product categories too.