Based on Make coupon field mandatory for a product category in WooCommerce answer, I am trying to implement a mandatory coupons for specific products in woocommerce.
Here is my code attempt:
add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
$targeted_ids = array(40, 41, 42, 43, 44); // The targeted product ids (in this array)
$coupon_code = 'summer1, summer2, summer3, summer4, summer5'; // The required coupon code
$coupon_applied = in_array( strtolower($coupon_code), WC()->cart->get_applied_coupons() );
// Loop through cart items
foreach(WC()->cart->get_cart() as $cart_item ) {
// Check cart item for defined product Ids and applied coupon
if( in_array( $cart_item['product_id'], $targeted_ids ) && ! $coupon_applied ) {
wc_clear_notices(); // Clear all other notices
// Avoid checkout displaying an error notice
wc_add_notice( sprintf( 'The product"%s" requires a coupon for checkout.', $cart_item['data']-
>get_name() ), 'error' );
break; // stop the loop
}
}
}
The code works perfectly to make a coupon mandatory but I need that ONE fo the products can be checkedout using only ONE of the coupons.
With the actual code if I add product ID 40 to the cart, is obligatory to add the 5 coupons, summer1, summer2, summer3, summer 4 and summer5, otherwise the checkout will be impossible. I would like the customer can make the checkout using any of the coupons for any of the products listed in the targeted_id array.
In other words, for all the products the use of coupon is mandatory but not necessarily a specific coupon, could be anyone of the listed in the code.
For example purposes I listed 5 products and 5 coupons, but in reality there are 100 products and 100 coupons
Thank you in advance