Weight-Based Flat Rate Shipping Cost
Recalculates your Flat Rate shipping price from the parcel weight using tiers you set, for example 4.95 up to 2 kg and 7.95 up to 10 kg.
Opens WPIDE on
Code
$wpide_weight_tiers = array( // Max weight => cost.
2 => 4.95,
5 => 6.50,
10 => 7.95,
);
$wpide_weight_extra = 0.50; // Cost per weight unit above the last tier.
add_filter( 'woocommerce_package_rates', function ( $rates, $package ) use ( $wpide_weight_tiers, $wpide_weight_extra ) {
$weight = 0.0;
foreach ( (array) $package['contents'] as $item ) {
$weight += (float) $item['data']->get_weight() * (int) $item['quantity'];
}
ksort( $wpide_weight_tiers );
$cost = null;
foreach ( $wpide_weight_tiers as $max => $price ) {
if ( $weight <= $max ) {
$cost = $price;
break;
}
}
if ( null === $cost ) {
$last = array_key_last( $wpide_weight_tiers );
$cost = $wpide_weight_tiers[ $last ] + ceil( $weight - $last ) * $wpide_weight_extra;
}
foreach ( $rates as $rate ) {
if ( 'flat_rate' !== $rate->get_method_id() ) {
continue;
}
$old = (float) $rate->get_cost();
$rate->set_cost( $cost );
if ( $old > 0 && $rate->get_taxes() ) {
$taxes = array();
foreach ( $rate->get_taxes() as $key => $tax ) {
$taxes[ $key ] = $tax * $cost / $old;
}
$rate->set_taxes( $taxes );
}
}
return $rates;
}, 20, 2 );
Notes
Weights use your store's weight unit, and above the last tier the extra cost is added for every unit over it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.