WordPress   

Add extra fee for COD payment method in WooCommerce checkout

This code snippet comes handy when we want to charge users an extra fee if they select Cash on Delivery payment method during checkout in a Woocommerce website. You can change the fee amount and label in the following code snippet according to your store requirements.

//Add Extra Fee for COD payment method
add_action( 'woocommerce_cart_calculate_fees','rp_woo_add_extra_cod_fee' );
function rp_woo_add_extra_cod_fee() {
    global $woocommerce;
    if ( is_admin() && ! defined('DOING_AJAX' )){
        return;
    }
    else{
        $chosen_gateway = WC()->session->chosen_payment_method;
        $fee = 10;
		$feeLabel = 'COD Fee';
        if ( $chosen_gateway == 'cod' && !empty($fee) && $fee !='0') { 
            WC()->cart->add_fee( $feeLabel, $fee, false, '' );
        }
    }
}

We have successfully added an extra fee for COD method. Now we need to add one more update to this code snippet so that it sets and unsets the extra fee when the users shuffle between different payment methods during the checkout.

//Add another check if user changes payment mehtod during checkout
add_action( 'wp_footer', 'rp_woo_add_fee_update_checkout' );
function rp_woo_add_fee_update_checkout() {
    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;
}

To add this funcitonlaity to your woocommerce website you just need to add these two short code snippets into active theme’s functions.php file.

Need a helping hand in fixing your website issues?

If you are facing any problems in implementing these code snippets and tutorials, you can hire us to fix your website issues.

Hire Us