Search code examples
phpwordpresswoocommercecustom-taxonomycoupon

Mandatory Coupon code for specific Woocommerce product category items


In Woocommerce, I'm trying to make a Coupon Code mandatory for all Products from a specific Category.

The following code (placed in functions.php) works well, but makes Coupon Codes mandatory for all Products regardless of the product category:

add_action('woocommerce_check_cart_items', 'make_coupon_code');

function make_coupon_code()
{
    global $woocommerce;
    if(is_cart() || is_checkout()){
        $my_coupon = $woocommerce->cart->applied_coupons;
        echo $woocommerce->cart->get_applied_coupons;
        if(empty($my_coupon))
        {
            wc_add_notice( '<strong>' . $btn['label'] . '</strong> ' . __( 'insert coupon code', 'woocommerce' ), 'error' );
        }
    }
}

Any ideas?

(the Product Category I'm trying to target is 'chef-masterclass')


Solution

  • Updated: The code below will prevent checkout for a mandatory coupon code that need to be applied for a specific product category:

    add_action( 'woocommerce_check_cart_items', 'mandatory_coupon_code' );
    function mandatory_coupon_code() {
        // HERE below -- Your settings
        $mandatory_coupon   = 'summer'; // <== Coupon code
        $product_categories = array( 'chef-masterclass' ); // <== Product category (Id, slug or name)
    
        $applied_coupons = WC()->cart->get_applied_coupons();
    
        // If coupon is found we exit
        if( in_array( $mandatory_coupon, $applied_coupons ) ) return;
    
        $found = false;
    
        // Loop through cart items to check for the product category
        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
            }
        }
    
        // Coupon not applied and product category found
        if( $found ){
            // Display an error notice preventing checkout
            $coupon_html = '<strong>"' . ucfirst( $mandatory_coupon ) . '"</strong>';
            $message = sprintf( __( 'Please enter the coupon code %s to checkout.', 'woocommerce' ), $coupon_html );
            wc_add_notice( $message, 'error' );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works