What can we help you with?
WooCommerce Shipping – Add Handling Fee based on Shipping Class
There might be few products on your store that need special packing and cost extra for the packing itself. And, some products require special delivery type hence require additional handling fee. How to add this to the shipping cost? You can add the below code snippet to functions.php in the theme folder.
add_filter( 'woocommerce_package_rates', 'ph_add_extra_cost_based_on_shipping_class', 10, 2);
if( ! function_exists('ph_add_extra_cost_based_on_shipping_class') ) {
function ph_add_extra_cost_based_on_shipping_class( $shipping_rates, $package ){
$handling_fee_based_on_shipping_class = array(
array(
'shipping_classes' => array( 'smart_phone', 'test'), //Enter an array of shipping class slug
'adjustment' => 70, // Enter the handling fee to be charged for the shipping class
),
array(
'shipping_classes' => array( 'shoe', 'electronic' ),
'adjustment' => 50,
),
);
$shipping_method_ids = array( 'wf_dhl_shipping' ); // Shipping method ID on which adjustment has to be applied
$adjustment = null;
foreach( $package['contents'] as $line_item ) {
$line_item_shipping_class = $line_item['data']->get_shipping_class();
if( ! empty($line_item_shipping_class) ) {
foreach( $handling_fee_based_on_shipping_class as $adjustment_data ) {
if( in_array( $line_item_shipping_class, $adjustment_data['shipping_classes']) ) {
$adjustment = ( $adjustment_data['adjustment'] > $adjustment ) ? $adjustment_data['adjustment'] : $adjustment;
}
}
}
}
if( ! empty($adjustment) ) {
foreach( $shipping_rates as $shipping_rate ) {
$shipping_method_id = $shipping_rate->get_method_id();
if( in_array($shipping_method_id, $shipping_method_ids) ) {
$shipping_rate->set_cost( (float) $shipping_rate->get_cost() + $adjustment );
}
}
}
return $shipping_rates;
}
}
With this solution you can add shipping class and add the handling fee required for that class, and assign the shipping class to those products that require additional handling fee.