How to make Coupon Mandatory for WooCommerce Product?

Offering discount coupons is a way to offer rewards and discounts on products to your customers. This is beneficial to your store as well as to the customer. The customer can purchase an item at a lower price, and your business generates revenue.

There are various ways of offering product discounts with usage restrictions. Usage restrictions prevent the overuse of discounts, which is not good for your business. There is the option of creating a coupon based on a minimum spend, per product category, product purchased, or email address. Creating WooCommerce product discount coupons available exclusively to members of your store not only prevents the over usage of a coupon, but it is also enticement for customers to register an account with your store.

Getting ready

Before doing any code modifications, it’s always a good idea to take a full backup of our site and make sure that we have FTP access or access to cPanel or Plesk or other control panel with access to a file manager.

If you wonder what is the best way to add code snippets to your site, have a look at our previous article about safely adding PHP code

Don’t forget to activate the use of coupons in your dashboard, by going to WooCommerce -> Settings -> General and checking the “Enable coupons” option.

Require coupon for single product

If you have a single product that you want it to only be available with the use of coupon, all you need is to know the product ID and the coupon code, and modify the following snippet to fit your needs:

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

Where:

  • $targeted_ids = array(37): Replace 37 with the ID of your product. You can add multiple products by separating the product IDs with a comma, ex array(37, 12, 99);
  • $coupon_code= 'summer2';: Replace summer2 with your coupon code.

Screenshot of woocommerce checkout when trying to add a product that requires coupon

Require coupon for all products in a specific category

If you want to require a coupon for all the products in a specific category, we can edit the above snippet as shown below:

add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
function mandatory_coupon_code() {
$product_categories = array( 'clothing' ); // Category ID or slug of targeted category
$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 ){
if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) && ! $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
}
}
}

Where:

  • $product_categories = array( 'clothing' );: Replace clothing with the slug, or the ID of the targeted category

Generate WooCommerce Coupon Shortcodes

Getting this functionality on your website is simple. You just have to add the piece of code below in the theme functions. The code allows you to display the coupon input field wherever you may like.

Follow the steps coming up to get this on your website:

You will have to add the code below to the Theme function. 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_shortcode( 'coupon_field', 'display_coupon_field' );
function display_coupon_field() {
    if( isset($_GET['coupon']) && isset($_GET['redeem-coupon']) ){
        if( $coupon = esc_attr($_GET['coupon']) ) {
            $applied = WC()->cart->apply_coupon($coupon);
        } else {
            $coupon = false;
        }
 
        $success = sprintf( __('Coupon "%s" Applied successfully.'), $coupon );
        $error   = __("This Coupon can't be applied");
 
        $message = isset($applied) && $applied ? $success : $error;
    }
 
    $output  = '
 

‘; $output .= isset($coupon) ? ‘

‘.$message.’

‘ : ”; return $output . ‘

‘; }

After adding the code to Theme Functions, you will have to display a message with a box for users to input the coupon code or simply a coupon input message.

This can be done by pasting the following shortcode to any place on your website you want to show it,
[coupon_field]

Wrapping up

Discounts are exciting, and rewarding members and loyal customers with exclusive offers is even more exiting! The code snippets presented in this article will enable you to:

  1. Require coupon for the sale of single product
  2. Require coupon for any product from a specific category.

Waqas

I hope you enjoy reading this blog post. If you want my team to do WooCommerce Maintenance for you, click here.

2 thoughts on “How to make Coupon Mandatory for WooCommerce Product?”

  1. Hello,

    Thanks for this great tutorial. Can you plase make a code example for a case when WooCommerce coupon is mandatory for all the products in the shop?

    I really appreciate any help you can provide.

    Regards

Leave a Comment

Your email address will not be published. Required fields are marked *