Allow specific products to be purchased only if a coupon is applied in Woocommerce

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply