0

I want to change total price depending payment method in checkout page , i have two payments method if the customer select Cash on delivery Total price become Total * 0.015 + Total Else the Total price remains unchanged

Lahcene
  • 23
  • 1
  • 3
  • Like this Total * 0.015 + Total OR Total * 0.015 = Total ??? – Tanmay Patel Apr 29 '20 at 04:28
  • Below Answer code is work like Total * 0.015 = Total. – Tanmay Patel Apr 29 '20 at 04:54
  • 1
    Does this answer your question? [Add a fee based on shipping method and payment method in Woocommerce](https://stackoverflow.com/questions/52138784/add-a-fee-based-on-shipping-method-and-payment-method-in-woocommerce) – Howard E Apr 29 '20 at 10:07

1 Answers1

1

Code goes in functions.php file of your active child theme (or theme) or also in any plugin file. This code is tested and works.

All payment methods are only available on Checkout page.

add_action('woocommerce_cart_calculate_fees','custom_handling_fee',10,1);
function custom_handling_fee($cart){
    if(is_admin() && ! defined('DOING_AJAX'))
        return;
    if('cod' === WC()->session->get('chosen_payment_method')){
        $extra_cost = 0.015;
        $cart_total = $cart->cart_contents_total; 
        $fee = $cart_total * $extra_cost;
        if($fee != 0)
        $cart->add_fee('COD Charge',$fee,true);
    }
}

You will need the following to refresh checkout on payment method change, to get it work:

add_action( 'wp_footer','custom_checkout_jqscript');
function custom_checkout_jqscript(){
    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;
}
Tanmay Patel
  • 1,770
  • 21
  • 28