如何在没有插件的情况下将 Woocommerce 优惠券应用于特定用户角色?

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

我已经在客户的 Wordpress 站点中实现了批发用户角色。最终目标是让批发用户在所有产品上享受 40% 的折扣,但如果他们花费 500.00 美元或更多,他们将获得购物车总购买量的额外 7% 折扣。我设置了动态定价的初始 40% 折扣,并为额外的 7% 创建了一张优惠券,无需用户输入优惠券代码即可自动应用于购物车。

唯一的问题是优惠券适用于所有用户(客户、管理员和经销商)并且不针对特定角色。谁能告诉我如何更改优惠券代码以将 only 应用于 "dealer" 的用户角色?需要看直播的可以看here!谢谢!

    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();
    }

}

您可以使用 current_user_can() 检查角色或能力:

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