0

I found my problem's solution from the link below: Allow specific products to be purchased only if a coupon is applied in Woocommerce

but this code is not working anyone help me

this is a code :

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
        }
    }
}
  • What is not working for you? Do you get an error message? Note: You copied and pasted the snippet from the linked answer. You have to change the product IDs and the phrase in `$coupon_code` – Uwe Aug 21 '22 at 13:15
  • yes i have changed product id and coupon code also registered coupon code in woocommerce. but there is no change/effect on cart page as shown in example. – Uzair Ahmed Aug 21 '22 at 13:43
  • 1
    So now debug. Do a `var_dump()` and `exit()` and check if your array is properly filled, if your if statement returns true or false. Report what is happening, so we can try to help. – Uwe Aug 21 '22 at 14:07
  • i am not good in programming. thats why i asked – Uzair Ahmed Aug 22 '22 at 07:01
  • You still have to try things and provide information about what is happening. Without that no one can actually help you. So firstly try `var_dump($coupon_applied); exit();` and see if it returns `bool(true)`. If it does not, that's the reason why it does not work. The second test would be inside your `foreach` loop `if( in_array( $cart_item['product_id'], $targeted_ids ) { var_dump(); exit(); }` To see if any of your product IDs would trigger your notice. – Uwe Aug 22 '22 at 12:04

0 Answers0