woocommerce_package_rates
Filters the shipping rates offered for a package in the cart. Hide, rename or reprice shipping methods based on the basket.
When it fires
WooCommerce applies this filter while it calculates shipping for each package (usually the whole cart), after every shipping method in the matching zone has added its rates. It runs for the classic cart and checkout and for the Cart and Checkout blocks.
The results are cached in the customer's session, so the filter only runs again when the package changes, for example when the cart or address changes.
Parameters
$ratesarray |
Package rates: WC_Shipping_Rate objects keyed by rate ID. |
|---|---|
$packagearray |
Package of cart items. |
What to return
The array of rates. Unset entries to hide methods. If you return something that isn't an array, WooCommerce treats it as no rates.
Example: Hide flat rate shipping for heavy baskets
add_filter( 'woocommerce_package_rates', function ( $rates, $package ) {
$weight = 0;
foreach ( $package['contents'] as $item ) {
if ( $item['data'] instanceof WC_Product && $item['data']->has_weight() ) {
$weight += (float) $item['data']->get_weight() * $item['quantity'];
}
}
if ( $weight <= 30 ) {
return $rates;
}
foreach ( $rates as $rate_id => $rate ) {
if ( 'flat_rate' === $rate->get_method_id() ) {
unset( $rates[ $rate_id ] );
}
}
return $rates;
}, 10, 2 );
Good to know
- While testing, turn on shipping debug mode (WooCommerce > Settings > Shipping) so cached rates are skipped. Turn it off again afterwards.
- Weights use the unit set under WooCommerce > Settings > Products.
- WooCommerce has a built-in setting to hide other rates when free shipping is available, so check the shipping settings before writing a snippet for that.