Add a fee based on shipping method and payment method in WooCommerce

Are you looking for an easy way to apply additional fees when a customer places an order with free shipping but wants to select Cash on Delivery payment?

WooCommerce gives you various options to design your online store in order to maximise the results of your efforts. You can add multiple codes and install a variety of plugins to make your website suit your needs.

Below is a code which allows you to set the amount of the fees and the conditions for when the fees are to be added to the checkout bill.

In order to install this option to your website, you will have to add a code to the theme functions of your active child theme.

Copy the code below and go to Dashboard > Themes > Theme editor > theme functions and paste it after the existing code.

You can change the amount of the fees by replacing it with the preset amount of 19 under the Your Setting part of the code.

add_action( 'woocommerce_cart_calculate_fees', 'add_cod_fee', 20, 1 );
function add_cod_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
 
    ## ------ Your Settings (below) ------ ##
    $your_payment_id      = 'cod'; // The payment method
    $your_shipping_method = 'free_shipping'; // The shipping method
    $fee_amount           = 19; // The fee amount
    ## ----------------------------------- ##
 
    $chosen_payment_method_id  = WC()->session->get( 'chosen_payment_method' );
    $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
    $chosen_shipping_method    = explode( ':', $chosen_shipping_method_id )[0];
 
    if ( $chosen_shipping_method == $your_shipping_method 
    && $chosen_payment_method_id == $your_payment_id ) {
        $fee_text = __( "Additional Charges", "woocommerce" );
        $cart->add_fee( $fee_text, $fee_amount, false );
    }
}
 
// Refresh checkout on payment method change
add_action( 'wp_footer', 'refresh_checkout_script' );
function refresh_checkout_script() {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url('order-received') ) :
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // On payment method change
        $('form.woocommerce-checkout').on( 'change', 'input[name="payment_method"]', function(){
            // Refresh checkout
            $('body').trigger('update_checkout');
        });
    })
    </script>
    <?php
    endif;
}

After Code:

As seen in the output, the additional fee for selecting COD is added and the total has changed. And that is all there is to it to add this functionality. Let us know what you think about it in the comments section below.

Leave a Reply