Search code examples
wordpresswoocommercecoupon

How can I apply a Woocommerce Coupon to a specific user role without a plugin?


I have implemented a wholesale user role into my client's Wordpress site. The end goal is to have the wholesale user have a 40 % discount on all products, but if they spend $500.00 or more, they get an additional 7% off of the total cart purchase. I set up the initial 40% discount with dynamic pricing and for the additional 7% I created a coupon to automatically be applied to the cart without the user having to enter the coupon code.

The only issue is that the coupon works for all users (customers, admin and dealer) and isn't role specific. Can anyone tell me how I can alter my coupon code to apply only to the user role for "dealer" ? If you need to see the live site, you can view that here! Thank you!

    add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );

function apply_matched_coupons() {
    global $woocommerce;

    $coupon_code = 'additionaldiscount'; // coupon code

    if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;

    if ( $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }

}

Solution

  • You can use current_user_can() to check a role or capability:

    if ( current_user_can('dealer') && $woocommerce->cart->cart_contents_total >= 500 ) {
        $woocommerce->cart->add_discount( $coupon_code );
        $woocommerce->show_messages();
    }