Search code examples
phpwordpresswoocommercecartdiscount

Shipping discount based on user roles in Woocommerce


I tried to implement a code snippet for functions.php that will apply a 50% discount to the delivery charge when the "admin" role and want to hide it goes in free delivery mode.

It does not work as I would like. What I am doing wrong?

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

Could anyone help complete this? Or atleast point to the right direction?


Solution

  • If you add return; before the adding the fee, nothing happen. Instead use this lightly changed code version:

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

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