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!
PHP Snippet: Add Fee If Shipping Class Is In The Cart @ WooCommerce Checkout
The only things you need to change in the snippet are:
- the shipping class ID, which you can find in this way for example
- 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 );
}
}