I’ve tried using this code:
//
/**
* Renders notices and prevents checkout if the cart
* does not contain a minimum number of products in a category
*/
function sww_check_category_for_minimum() {
// set the minimum quantity in the category to purchase
$min_quantity = 1;
// set the id of the category for which we're requiring a minimum quantity
$category_id = 90;
// get the product category
$product_cat = get_term( $category_id, 'product_cat' );
$category_name = '<a href="' . get_term_link( $category_id, 'product_cat' ) . '">' . $product_cat->name . '</a>';
// get the quantity category in the cart
$category_quantity = sww_get_category_quantity_in_cart( $category_id );
if ( $category_quantity < $min_quantity ) {
// render a notice to explain the minimum
wc_add_notice( sprintf( '<strong>A minimum quantity of the choosen Brewer has not been met. <br /> (Kuerig 140 Reqiures A Minimum of 4 Boxes to Order)<br />(Kuerig 150 Reqiures A Minimum of 8 Boxes to Order)<br />(Kuerig K3000SE Reqiures A Minimum of 12 Boxes to Order)<br />(Kuerig Bolt Carafe Reqiures A Minimum of 10 Boxes to Order)</strong><br />'), 'error' );
}
}
add_action( 'woocommerce_check_cart_items', 'sww_check_category_for_minimum' );
/**
* Returns the quantity of products from a given category in the WC cart
*
* @param int $category_id the ID of the product category
* @return in $category_quantity the quantity of products in the cart belonging to this category
*/
function sww_get_category_quantity_in_cart( $category_id ) {
// get the quantities of cart items to check against
$quantities = WC()->cart->get_cart_item_quantities();
// start a counter for the quantity of items from this category
$category_quantity = 0;
// loop through cart items to check the product categories
foreach ( $quantities as $product_id => $quantity ) {
$product_categories = get_the_terms( $product_id, 'product_cat' );
// check the categories for our desired one
foreach ( $product_categories as $category ) {
// if we find it, add the line item quantity to the category total
if ( $category_id === $category->term_id ) {
$category_quantity += $quantity;
}
}
}
return $category_quantity;
}
The code displays on the cart page and prevents you from checking out even if you have the right product categories. I do not know how to check to see if the right product ID is in the cart for the function to run and display the error.