I am trying to build a WooCommerce cart rule functionality. It should work like this:
When the user's role is "Wholesaler", they must add to the cart at least 2 or 3 items (depending on the category) of the same product category. Once that condition is met, they could add any product to the cart no matter the rules set before.
E.g:
- Minimum order on socks: 3
- Minimum order on hats: 3
- Minimum order on shirts: 2
Scenarios:
- If the customer adds at least 3 hats, the other two minimum rules should be avoided.
- If the customer adds 1 sock and 2 hats, they will not be able to complete the order unless they adds 2 more socks or 1 hat.
Based on Prevent WooCommerce checkout if minimum quantity for a category is not reached unless another category is added answer code, this is my code attempt:
function action_woocommerce_check_cart_items() {
// Only run on the cart or checkout pages
if ( is_cart() || is_checkout() ) {
// Minimum
$minimum = 3;
// Category
$category1 = 'socks';
$category2 = 'hats';
// Initialize
$total_socks = 0;
$total_hats = 0;
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
// Product id
$product_id = $cart_item['product_id'];
// Has certain category
if ( has_term( $category1, 'product_cat', $product_id ) ) {
// Add to total
$total_socks += $cart_item['quantity'];
}
elseif ( has_term( $category2, 'product_cat', $product_id ) ) {
// Add to total
$total_hats += $cart_item['quantity'];
}
}
// When total is greater than 0 but less than the minimum
if ( ($total_socks > 0 && $total_socks < $minimum) && ( $total_hats > 0 && $total_hats < $minimum ) ) {
// Notice
wc_add_notice( sprintf( __( 'A minimum of %s products are required from the %s category before checking out.', 'woocommerce' ), $minimum, $category1 ), 'error' );
// Optional: remove proceed to checkout button
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );
}
}
}
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );
But I couldn’t add a user role check and mixed with the other categories missing on the script (socks and shirts), any advice?