Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

Code

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 add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.