Add Checkout Fee for Cash On Delivery Payment Method

In WooCommerce, you may want to apply an additional fee when customers choose the Cash On Delivery (COD) payment method. This snippet allows you to add a fixed fee to the checkout total when COD is selected.

/**
 * Snippet Name:  Add Checkout fee if payment method is Cash On Delivery
 * Snippet Author:  wpsnippets.dev
 */

// Add the fixed fee for the specific payment method
function wps_cod_fixed_fee() {
    if( 'cod' == WC()->session->get( 'chosen_payment_method' ) ) { // The payment method ID
        WC()->cart->add_fee( 'Cash on delivery fee', 10 ); // The fee label and amount
    }
}
add_action( 'woocommerce_cart_calculate_fees', 'wps_cod_fixed_fee', 10 );

// Show the fixed fee amount right of the payment method name
function wps_show_fee_label_with_cod( $icon_html, $gateway_id ) {
    if( 'cod' === $gateway_id ) {
        return '<small>(' . wc_price( 10 ) . ' fee)</small>'; // The fee amount
    }
    return $icon_html;
}
add_filter( 'woocommerce_gateway_icon', 'wps_show_fee_label_with_cod', 10, 2 );

// JavaScript to update the totals on payment method selection
function wps_update_checkout_totals() { ?>
<script>
    jQuery( function( $ ) {
        $( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
            $( 'body' ).trigger( 'update_checkout' );
        });
    });
</script>
<?php }
add_action( 'wp_footer', 'wps_update_checkout_totals' );

Code Explanation

  • Add Fixed Fee for Cash On Delivery Payment Method:
    • This part of the code adds a fixed fee to the cart total if the chosen payment method is Cash On Delivery (COD). It checks the payment method selected by the customer and adds a fee of $10 to the cart if COD is chosen.
  • Show Fixed Fee Amount for COD Payment Method:
    • This part of the code displays the fixed fee amount next to the Cash On Delivery payment method name. It modifies the HTML output for the payment method icon to include the fee amount.
  • Update Checkout Totals Dynamically:
    • This part of the code adds JavaScript to update the checkout totals dynamically when the payment method is changed. It listens for changes in the payment method input field and triggers the update_checkout event to recalculate the totals.

Overall, this snippet enhances the WooCommerce checkout process by adding a fixed fee for the Cash On Delivery payment method and dynamically updating the checkout totals.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top