Search code examples
phpwordpresswoocommercecartdiscount

Automatically apply discount to user role if no coupon is applied in Woocommerce


I have this code below but I want it to be effective only if the user is not using another code, and if the user uses another coupon, then disable this one.

based on "Apply a discount for a specific user role in Woocommerce" answer code, I've been trying to look how to check if there's any coupon but can't figure it out.

// Applying conditionally a discount for a specific user role
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_on_user_role( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit

    // Only for 'company' user role
    if ( ! current_user_can('affiliate') )
        return; // Exit

    // Only for 'company' user role
    if ( ! current_user_can('affiliate') )
        return; // Exit

    // HERE define the percentage discount
    $percentage = 15;

    $discount = $cart->get_subtotal() * $percentage / 100;
    // Applying discount
    $cart->add_fee( sprintf( __("Affiliate Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}

Any help is appreciated.


Solution

  • Try the following that will set a custom discount based on specific user role, if there is no applied coupons in cart:

    // Applying conditionally a discount for a specific user role and no applied coupons
    add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
    function discount_based_on_user_role( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return; // Exit
    
        // Only for 'affiliate' user role
        if ( ! current_user_can('affiliate') )
            return; // Exit
    
        // Only if there is no applied coupons in cart
        if ( ! empty( $cart->get_applied_coupons() ) )
            return; // Exit
    
        // HERE define the percentage discount
        $percentage = 15;
    
        $discount = $cart->get_subtotal() * $percentage / 100; // Calculation
    
        // Applying discount
        $cart->add_fee( sprintf( __("Affiliate Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
    }
    

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