In Woocommerce I am trying to add a shipping fee if a cart item has a specific shipping class assigned to the related product. I would like this shipping fee to be multiplied by the cart item quantity…
I have this working when a product is added to the cart and the quantity is increased and the additional shipping fee is increased also. However if I add another product with the same shipping class and increase the quantity the additional fee does not increase.
This is my code:
// Add additional fees based on shipping class
function woocommerce_fee_based_on_shipping_class( $cart_object ) {
global $woocommerce;
// Setup an array of shipping classes which correspond to those created in Woocommerce
$shippingclass_dry_ice_array = array( 'dry-ice-shipping' );
$dry_ice_shipping_fee = 70;
// then we loop through the cart, checking the shipping classes
foreach ( $cart_object->cart_contents as $key => $value ) {
$shipping_class = get_the_terms( $value['product_id'], 'product_shipping_class' );
$quantity = $value['quantity'];
if ( isset( $shipping_class[0]->slug ) && in_array( $shipping_class[0]->slug, $shippingclass_dry_ice_array ) ) {
$woocommerce->cart->add_fee( __('Dry Ice Shipping Fee', 'woocommerce'), $quantity * $dry_ice_shipping_fee ); // each of these adds the appropriate fee
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'woocommerce_fee_based_on_shipping_class' ); // make it all happen when Woocommerce tallies up the fees
How can I make it work for additional cart items too?