Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Frontend Snippets][Add a surcharge to cart and checkout] Add a percentage based surcharge to all transactions
/**
* Add a 1% surcharge to your cart / checkout
* change the $percentage to set the surcharge to a value to suit
*/
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, '' );
}
@digitalchild

This comment has been minimized.

Copy link

@digitalchild digitalchild commented May 21, 2018

This should be updated to use WC() instance instead of the global $woocommerce

@tremblayly

This comment has been minimized.

Copy link

@tremblayly tremblayly commented Oct 22, 2019

Can this be used, say to offer customers an option to purchase shipping insurance, where if they check to add insurance, the cart/checkout will add a 2.5% surcharge (for insurance) to the order.

@helgatheviking

This comment has been minimized.

Copy link

@helgatheviking helgatheviking commented Jul 1, 2020

/**
 * Add a 1% surcharge to your cart / checkout
 * change the $percentage to set the surcharge to a value to suit
 */
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {

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

	$percentage = 0.01;
	$surcharge = ( WC()->cart->get_cart_contents_total() + WC()->cart->get_shipping_total()) * $percentage;	
	WC()->cart->add_fee( __( 'Surcharge', 'text-domain' ), $surcharge, true, '' );

}
@fdeross

This comment has been minimized.

Copy link

@fdeross fdeross commented Oct 28, 2020

@helgatheviking This code is causing a syntax error.

syntax error, unexpected 'get_cart_contents_total' (T_STRING)

@helgatheviking

This comment has been minimized.

Copy link

@helgatheviking helgatheviking commented Oct 28, 2020

@fdeross looks like a copy/paste fail on my part. check the update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment