I have currently 2 shipping zones (France, Europe) and each of them have several delivery option, including flat-rate. These flat-rate options have a different equation to calculate the fee based on item qty with A B and C three different shipping class. It easy enough to do with the advanced costs options native to Woocommerce.
My problem is that I would like to set a minimum and a maximum for the delivery fees, and these min / max are only for flat-rate option and different from a geographical zone to another. In a nutshell :
- France flat-rate method :
2€ + (1€*[qtyA] + 2€*[qtyB] + 5€*[qtyC])
withMin = 7
andMax = 15
- Europe flat-rate method :
6€ + (2€*[qtyA] + 4€*[qtyB] + 8€*[qtyC])
withMin = 10
andMax = 25
I have tried to write some code in function.php with conditions relying on the shipping zone and shipping method but neither my min or max are applied.
Hopefully maybe someone will be able to help as this is driving me nuts.
function maximum_shipping_rates_function( $rates, $package ) {
$methods = WC()->shipping()->get_shipping_methods();
$shipping_limit = 10.50; // I set my minimul to 10.50€
$only_apply_to_rates = array( 'shipping_method_0_flat_rate2', 'flat_rate' ); // I put here the Shipping method ID thqt I get by inspecting the option on the checkout page
// Loop through all rates
foreach ( $rates as $rate_id => $rate ) {
// Skip the shipping rates that are not in the list
if ( ! in_array( $rate_id, $only_apply_to_rates ) ) {
continue;
}
// Check if the rate is higher than my maximum
if ( $rate->cost > $shipping_limit ) {
$rate->cost = $shipping_limit;
// Recalculate shipping taxes
if ( $method = $methods[ $rate->get_method_id() ] ) {
$taxes = WC_Tax::calc_shipping_tax( $rate->cost, WC_Tax::get_shipping_tax_rates() );
$rate->set_taxes( $method->is_taxable() ? $taxes : array() );
}
}
}
return $rates;}
add_action( 'woocommerce_package_rates', 'maximum_shipping_rates_function', 10, 2 );