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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.