X

How To Add a Surcharge by Delivery Country in WooCommerce

Snippets by IsItWP

Are you looking for a way to add a surcharge by delivery country in WooCommerce? While there’s probably a plugin for this, we have created a quick code snippet that you can use to add a surcharge by delivery country in WooCommerce.

Instructions:

All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;
 
	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;

 	$county 	= array('US');
	$percentage 	= 0.01;

	if ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ) :
		$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
		$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
	endif;
 
}

You can reverse this to exclude specific countries from the surcharge list by changing in_array to !in_array on line 11. You can change the $percentage variable on line 9 to adjust the surcharge percent.

Or, to apply a 1% surcharge to your cart for all transactions, use this code:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
  global $woocommerce;

	if ( is_admin() && ! defined( 'DOING_AJAX' ) )
		return;

	$percentage = 0.01;
	$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;	
	$woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );

}

These snippets were created by WooCommerce.

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: How to Create an Online Store and 50+ best WooCommerce themes for your online store.

Comments   Leave a Reply

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!