I have 2 shipping classes.
One free shipping.
The other is 6 pieces for 1 piece shipping (id=43)
add_filter( 'woocommerce_package_rates', 'woocommerce_cool_rates' );
function woocommerce_cool_rates( $rates) {
if ( ! WC()->cart->is_empty() ) {
$class_cool = array(43);
$found = false;
$item_qty = 0;
foreach( WC()->cart->get_cart() as $cart_item ){
$item_shipping_class_id = $cart_item['data']->get_shipping_class_id();
if( in_array( $item_shipping_class_id, $class_cool) ){
$found = true; /* Target shipping class found */
$item_qty += $cart_item['quantity'];
$item_quantity = floor(($item_qty + 5) / 6);
}
}
}
foreach ($rates as $rate_key => $rate) {
if ($found) {
$cool_cost = $rates[$rate_key]->cost;
$new_cost = $cool_cost * $item_quantity;
$rates[$rate_key]->cost = $new_cost;
$rates[$rate_key]->taxes = array();
$rates[$rate_key]->set_taxes(0);
}
}
return $rates;
}
This time, we have added a new shipping item.
It is a product of ‘flat_rate’.
However, with the above source, the quantity of the ‘flat_rate’ item cannot be calculated.
Therefore, I wrote the source as follows, but it does not work well.
add_filter( 'woocommerce_package_rates', 'woocommerce_package_rates');
function woocommerce_package_rates( $rates) {
if ( ! WC()->cart->is_empty() ) {
$class_cool = array(43);
$found = false;
$item_qty = 0;
foreach( WC()->cart->get_cart() as $cart_item ){
$item_shipping_class_id = $cart_item['data']->get_shipping_class_id();
if( in_array( $item_shipping_class_id, $class_cool) ){
$found = true; /* Target shipping class found */
$item_qty += $cart_item['quantity'];
$item_quantity = floor(($item_qty + 5) / 6);
}
}
}
$total_shipping_cost = 0;
foreach ($rates as $rate_key => $rate) {
if ($rate->get_method_id() == 43) {
$cool_cost = $rates[$rate_key]->cost;
$new_cost = $cool_cost * $item_quantity;
$rates[$rate_key]->cost = $new_cost;
} elseif($rate->get_method_id() !== 43) {
$total_shipping_cost += $rate->get_cost();
}
}
return $rates;
}
Please let me know how this mix of 3 shipping costs works.