If two different shipping classes exist in cart then subtotal them in WooCommerce

I'm trying to achieve the following in WooCommerce: If a customer adds to cart a product from a specific category then shipment will cost $30 for example and if the customer increased the quantity of that product to 2 quantity then the shipment will cost $60 as so on I did that using 2 things: Advanced Flat Rate Shipping For WooCommerce plugin, Adding the following code in my theme functions.php file, to multiply the shipment cost if quantity increase, which is : add_filter( 'woocommerce_package_rates', 'multiply_shipping_cost_by_item_count', 10, 2 ); function multiply_shipping_cost_by_item_count( $rates, $package ) { $item_count = WC()->cart->get_cart_contents_count(); foreach ( $rates as $rate_key => $rate ) { $rates[$rate_key]->cost *= $item_count ; } return $rates; } And it works like magic, but now I faced an issue which when another product from another category is added to cart, then you have now 2 shipment methods, what I want to do is modify the code above to sum the shipment methods and add to cart total. Here is an explicit screenshot: I look it up without success. I really tried my best to describe this issue.

Comment (1)

Jese Leos

August 19, 2024

Verified user

You have a WooCommerce store where shipping costs are calculated based on the quantity of items in the cart. If someone adds more of the same product, the shipping cost increases proportionally. You've already set this up using a plugin and some custom code. Now, the challenge is that when a customer adds products from different categories (which might have different shipping methods or costs), you want to add up the shipping costs from each category instead of just multiplying by the quantity. We need to modify your existing code so that it does two things: 1.Calculate the shipping cost for each product/category separately. 2.Add up all these costs to get a total shipping cost. add_filter( 'woocommerce_package_rates', 'sum_shipping_costs_for_different_shipping_classes', 10, 2 ); function sum_shipping_costs_for_different_shipping_classes( $rates, $package ) { $shipping_total = 0; foreach ( $rates as $rate_key => $rate ) { $item_count = 0; // Loop through each item in the cart to check if it matches the shipping class foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { if ( $rate->method_id === 'your_shipping_method_id' && $cart_item['data']->get_shipping_class_id() == $rate->get_shipping_class_id() ) { $item_count += $cart_item['quantity']; } } // Multiply the rate cost by the item count $rate->cost *= $item_count; $shipping_total += $rate->cost; } // Set the calculated total shipping cost foreach ( $rates as $rate_key => $rate ) { $rates[$rate_key]->cost = $shipping_total; } return $rates; }

You’ll be in good company