Home > Mobile >  Extra fee based on user ID, user role and payment method in WooCommerce checkout
Extra fee based on user ID, user role and payment method in WooCommerce checkout

Time:04-17

I have a piece of code that adds a small fee to the checkout for a certain user role (b2bcustomer). Everything works OK.

Now I would like one particular user ID in this user role (b2bcustomer) not to be charged a fee.

I tried to complete the code below, but the fee for this user ID is still charged. Any advice?

Code in functions.php:

add_action( 'woocommerce_cart_calculate_fees', 'b2b_fee_for_gateway' );
   
function b2b_fee_for_gateway() {
$user_id = get_current_user_id(); /*added*/
    
    if(is_checkout() && WC()->customer->get_role() != current_user_can( 'b2bcustomer' ) && ($user_id != 1083)) /*added && ($user_id != 1083)*/
    return;
   
    global $woocommerce;
   
    $chosen_gateway = $woocommerce->session->chosen_payment_method;
  
    if ( $chosen_gateway != 'cod' && current_user_can( 'b2bcustomer' ) && ($user_ID != 1083)) 
       
    $surcharge = 10;   
        $woocommerce->cart->add_fee( 'B2B processing cost', $surcharge, true, '');
   
  }
 
}

CodePudding user response:

Some comments/suggestions regarding your code attempt/question

  • The use of global $woocommerce; is not necessary, since $cart is passed to the callback function
  • You can group the conditions but also list them 1 by 1 for clarity. It is certainly not necessary to repeat the same conditions several times
  • But the most important, given the chosen payment method. In WooCommerce checkout when choosing a payment method, checkout totals are not refreshed. So something additional is required to refresh checkout "order review" section

So you get:

function action_woocommerce_cart_calculate_fees( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // 1. Only for 'b2bcustomer' user role
    if ( ! current_user_can( 'b2bcustomer' ) ) return;

    // 2. Exclude certain user ID
    if ( get_current_user_id() == 1083 ) return;

    // 3. Only for 'cod' payment method
    if ( WC()->session->get( 'chosen_payment_method' ) != 'cod' ) return;
    
    // Fee
    $surcharge = 10;   

    // Applying
    $cart->add_fee( __( 'B2B processing cost', 'woocommerce' ), $surcharge, true, '' );
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );

// jQuery - Update checkout on method payment change
function action_wp_footer() {
    if ( is_checkout() && ! is_wc_endpoint_url() ) :
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $( 'form.checkout' ).on( 'change', 'input[name="payment_method"]', function() {
            $( document.body ).trigger( 'update_checkout' );
        });
    });
    </script>
    <?php
    endif;
}
add_action( 'wp_footer', 'action_wp_footer' );
  • Related