基于 Woocommerce 中用户角色的运费折扣

Shipping discount based on user roles in Woocommerce

我尝试为 functions.php 实现一个适用的代码片段 当 "admin" 角色并想要时,运费可享受 50% 的折扣 隐藏它进入免费送货模式。

它没有像我想要的那样工作。我做错了什么?

add_action( 'woocommerce_cart_calculate_fees','discount_based_on_user_role_and_payment', 20, 1 );
function discount_based_on_user_role_and_payment( $cart) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;
    $discount = WC()->cart->shipping_total/2;
if ( $discount >0 && !current_user_can('administrator') )
    return;
    $cart->add_fee( sprintf( __("Chiết khấu", "woocommerce")), -$discount, true );
}

有人可以帮忙完成吗?或者至少指向正确的方向?

如果您在添加费用之前添加 return;,则不会发生任何事情。 而是使用这个稍微改变的代码版本:

add_action( 'woocommerce_cart_calculate_fees','discount_based_on_user_role_and_payment', 20, 1 );
function discount_based_on_user_role_and_payment( $cart) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; 

    $discount = $cart->shipping_total / 2;

    if ( $discount > 0 && current_user_can('administrator') ) {
        $cart->add_fee( sprintf( __("Chiết khấu", "woocommerce")), -$discount, true );
    }
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。