In a store with multiple product categories, you may run targeted promotions for specific categories to drive bulk purchases or any other kind of promotions. However, at times you might also need to restrict how these promotions are applied.
Using the provided code snippet, you can restrict the sale of products within a specific category by requiring a coupon code at checkout. This ensures that discounts are exclusively available to customers who are aware of and actively use the promotion during the checkout process.
Solution: Make a Coupon Code Mandatory for Specific WooCommerce Product Category
The code requires customers to apply a coupon code when their cart items belongs to a specific category as defined in the code. If a product from the specified category is present, it prevents the checkout process.
add_action( 'woocommerce_check_cart_items', 'ts_mandatory_coupon_code' ); function ts_mandatory_coupon_code() { // Set your product categories in the array (can be term IDs, slugs or names) $product_categories = array( 'electronics' ); $found = false; // Loop through cart items to check for the product categories foreach ( WC()->cart->get_cart() as $cart_item ){ if( has_term( $product_categories, 'product_cat', $cart_item['product_id'] ) ){ $found = true; // cart item from the product category is found break; // We can stop the loop } } // If not found we exit if( ! $found ) return; // exit $applied_coupons = WC()->cart->get_applied_coupons(); // Coupon not applied and product category found if( is_array($applied_coupons) && sizeof($applied_coupons) == 0 ) { // Display an error notice preventing checkout $message = __( 'Please enter a coupon code to be able to checkout.', 'woocommerce' ); wc_add_notice( $message, 'error' ); } }
This to the shop owners who are running or planning to run BOGO offers on their WooCommerce store…
BOGO deals are great for increasing your sales, but have you thought about which offers are bringing you more revenue and which offers are not performing that great?
Don’t just set a BOGO deal, track the revenue generated by your deals in real-time with the Flexi BOGO for WooCommerce plugin.
Output
When a customer adds products from the specified category, “electronics,” and attempts to proceed to checkout without applying a coupon, the checkout process is restricted.
While discussing how to make coupon codes mandatory, you may also find it useful to explore how to hide the coupon code field for specific products on cart and checkout pages. For instance, store owners may want to hide the coupon code field entirely for certain products, such as low-priced ones. This approach can help reduce cart abandonment by streamlining the checkout process for these products.