# Surcharge for a Payment Method

> Adds a fee when the shopper chooses a specific payment method, for example cash on delivery, and updates the totals as soon as they switch methods.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, fees, payments, checkout
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-payment-method-fee/

## Code

```php
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) {
    $gateway    = 'cod';                  // Payment method ID.
    $fixed      = 2.00;                   // Fixed fee, 0 for none.
    $percentage = 0;                      // Percentage of the cart total, 0 for none.
    $label      = 'Cash on delivery fee'; // Name shown in the totals.

    if ( ( is_admin() && ! wp_doing_ajax() ) || ! WC()->session ) {
        return;
    }

    if ( WC()->session->get( 'chosen_payment_method' ) !== $gateway ) {
        return;
    }

    $base   = (float) $cart->get_cart_contents_total() + (float) $cart->get_shipping_total();
    $amount = $fixed + ( $base * $percentage / 100 );

    if ( $amount > 0 ) {
        $cart->add_fee( $label, round( $amount, wc_get_price_decimals() ), true );
    }
} );

add_action( 'wp_footer', function () {
    if ( function_exists( 'is_checkout' ) && is_checkout() && ! is_wc_endpoint_url() ) {
        echo "<script>jQuery(function($){ $('form.checkout').on('change', 'input[name=\"payment_method\"]', function(){ $(document.body).trigger('update_checkout'); }); });</script>\n";
    }
} );
```

## Notes

Set $gateway to the payment method ID (cod, bacs, cheque, or the ID of your gateway) and choose a fixed or percentage fee.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Surcharge for a Payment Method" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
