WooCommerce: Add Checkout Fee Based On Shipping Class

Whether you’re dealing with bulky items, fragile goods, or specific shipping items, you can leverage WooCommerce’s flexibility and implement a fee structure that accurately reflects shipping complexities, improves profit margins, and enhances overall order management.

This tutorial gives you a practical solution – dynamically adding checkout fees based on whether a given shipping class is in the cart.

Enjoy!

The code below will check if the cart contains a given shipping class ID, and if yes it will dynamically add a checkout fee. This works with the WooCommerce Checkout Block as well.

PHP Snippet: Add Fee If Shipping Class Is In The Cart @ WooCommerce Checkout

The only things you need to change in the snippet are:

  1. the shipping class ID, which you can find in this way for example
  2. the fee name, amount, and true/false in case it’s taxable or not
/**
 * @snippet       Checkout Fee If Shipping Class @ Woo Cart
 * @how-to        businessbloomer.com/woocommerce-customization
 * @author        Rodolfo Melogli, Business Bloomer
 * @testedwith    WooCommerce 9
 * @community     https://businessbloomer.com/club/
 */

add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_checkout_fee_if_shipping_class' );
		   
function bbloomer_checkout_fee_if_shipping_class( $cart ) {
	$shipping_class_target = 15355;
	$in_cart = false;
	$qty = 0;
	foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
		if ( $values['data']->get_shipping_class_id() == $shipping_class_target ) {
			$in_cart = true;
			break;
		} 
	}	
	if ( $in_cart ) {
		$cart->add_fee( 'Bulky Delivery', 9.99, true );
	}
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *