1

I am trying to have mandatory Coupons when checking out for specific products in WooCommerce. I tried Allow specific products to be purchased only if a coupon is applied in Woocommerce answer code, which works perfectly.

However it allows to define only one coupon code at a time.

My client has 13 different Sales Agents that she'd like to assign coupons to.

Is there a way to define more coupons in an array (or something similar)?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

0

For multiple coupon codes, use the following:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupons_for_specific_items' );
function mandatory_coupons_for_specific_items() {
    $targeted_ids    = array(37); // Your targeted product ids (in this array)
    $coupon_codes    = array('summer2', 'summer4'); // The required coupon codes (in this array)
    $applied_coupons = array_intersect( array_filter( array_map( 'sanitize_title', $coupon_codes) ), 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 ) && empty( $applied_coupons ) ) {
            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
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should work.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399