Handling Fee per Item in a Shipping Class
Charges an extra handling fee for each unit from a shipping class such as "fragile" or "oversized", listed as its own line in the totals.
Opens WPIDE on
Code
$wpide_class_fee = array(
'class' => 'fragile', // Shipping class slug.
'amount' => 2.50, // Fee per unit.
'label' => 'Fragile item handling', // Line label.
);
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) use ( $wpide_class_fee ) {
if ( is_admin() && ! wp_doing_ajax() ) {
return;
}
$units = 0;
foreach ( $cart->get_cart() as $item ) {
if ( $item['data']->get_shipping_class() === $wpide_class_fee['class'] ) {
$units += (int) $item['quantity'];
}
}
if ( $units > 0 ) {
$cart->add_fee( sprintf( '%s (x%d)', $wpide_class_fee['label'], $units ), $units * $wpide_class_fee['amount'], true );
}
} );
Notes
Use the shipping class slug from WooCommerce > Settings > Shipping > Classes.
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.