How to make Coupon Mandatory for WooCommerce Product

Are you looking for a way to allow specific products to be purchased only if a coupon is applied? Then no look no more!

Making items available only when a coupon code has been added can be used in professional marketing of the products where you want some particular group of people to receive the product.

WooCommerce gives you the ability to modify your page such that it becomes the ideal online store for you. Below is a code which will give your online store the functionality of making a specific product available when a coupon code is added.

Adding it to your site is just a matter of minutes. You will have to add the code below to the Theme functions of your active child theme.

Just go to Dashboard > Appearance > Theme Editor > Theme Functions and add the following code to the end of the existing code and click Update File

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
        }
    }
}

After Code:

As seen in the output, whenever such products will be added to the cart a message will be displayed saying that a coupon is required to check out.

That is all there is to add this functionality. Let us know what you think in the comments section below.

Leave a Reply