I want to charge extra fee if any one select COD as payment method.
Suppose if the cart amount is 10 to 1000 INR COD charges will be RS.50/- and 1001 to 2000 then COD charges will be RS.100- and so on.
I am using "Add fee for Cash on delivery payment method (cod) in Woocommerce" answer code, and I need some more customizations.
You could use a PHP switch
statement that takes the cart subtotal rounded up to the nearest power of 1000, and then base your fee of that. So for instance a subtotal of anything between 1001 and 2000 (including 2000) will be rounded to 2000. Which will be interpreted by the switch statement and a fee of 100 will be assigned.
The default in the switch statement will take care of anything higher than any of the cases you add to it.
// Add a custom fee based on cart subtotal
add_action( 'woocommerce_cart_calculate_fees', 'custom_cod_fee', 10, 1 );
function custom_cod_fee ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( 'cod' === WC()->session->get('chosen_payment_method') ) {
switch ( ceil( $cart->subtotal / 1000 ) * 1000 ) {
case "1000": // 0 to 1000
$fee = 50;
break;
case "2000": // 1001 to 2000
$fee = 100;
break;
case "3000": // 2001 to 3000
$fee = 150;
break;
case "4000": // 3001 to 4000
$fee = 200;
break;
case "5000": // 4001 to 5000
$fee = 250;
break;
default: // anything higher, no fee
$fee = '';
}
if ( !empty( $fee ) ) $cart->add_fee( 'COD Fee', $fee, true );
}
}
And obviously you would need the code that will update the checkout if you change payment gateways:
// jQuery - Update checkout on methode payment change
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;
}