4

I am working on a woocommerce website and I am trying to restrict a product to be purchased only if a coupon is applied for it, so it should not be processed without adding a coupon code. User must enter a coupon code to be able to order this specific product (not on all other products).

Any help is appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Zain Ali
  • 117
  • 3
  • 9

1 Answers1

5

For defined products, the following code will not allow checkout if a coupon is not applied, displaying an error message:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_for_specific_items' );
function mandatory_coupon_for_specific_items() {
    $targeted_ids   = array(37); // The targeted product ids (in this array)
    $coupon_code    = 'summer2'; // 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
        }
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

enter image description here

And in checkout:

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • i added this in function.php and then created a coupon for a specific product, but it proceed to checkout without coupon code? am i doing it wrong? – Zain Ali May 12 '19 at 19:33
  • @ZainAli I have tested again this code and it works perfectly… So it seems that you have not set the correct product ID or coupon code. – LoicTheAztec May 12 '19 at 19:46
  • ok 1 more question this is only for 1 product so if i want to put this condition on another product so do i have to copy paste this function or what? – Zain Ali May 12 '19 at 19:59
  • @ZainAli No you can add as any product ids (integers) as you want in the array like: `$targeted_ids = array(37, 52, 63);` – LoicTheAztec May 12 '19 at 20:02
  • ok one last thing to ask if i want the coupon from what i have added from woocommerce how can i do that? instead of $coupon_code = 'summer2'; i want it to find coupon from panel. can we do that? – Zain Ali May 14 '19 at 20:45
  • question posted – Zain Ali May 14 '19 at 21:05
  • 1
    yes i was just applying it, it works and it worked greatly thank you :) – Zain Ali May 14 '19 at 23:03
  • @LoicTheAztec do you or anyone know how to add multiple coupon codes in `$coupon_code = 'summer2';` This doesnt work: `$coupon_code = array('test-zvojrmtg6f','test-0meujlatns');` – Liv Apr 01 '20 at 07:00