Skip to content

Instantly share code, notes, and snippets.

@swoboda
Last active July 13, 2020 22:30
Show Gist options
  • Save swoboda/df06a72a63c30425d7a1 to your computer and use it in GitHub Desktop.
Save swoboda/df06a72a63c30425d7a1 to your computer and use it in GitHub Desktop.
hide_shipping_when_free_is_available
<?php
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );
/**
* Hide shipping rates when free shipping is available: https://docs.woothemes.com/document/hide-other-shipping-methods-when-free-shipping-is-available/
*
* @param array $rates Array of rates found for the package
* @param array $package The package array/object being shipped
* @return array of modified rates
*/
function hide_shipping_when_free_is_available( $rates, $package ) {
// Only modify rates if free_shipping is present
$free_shipping_rate_key = false;
foreach ( $rates as $rate_key => $rate ) {
$rate_key_exploded = explode( ':', $rate_key );
if ( $rate_key_exploded[0] === 'free_shipping' ) {
$free_shipping_rate_key = $rate_key;
}
}
if ( $free_shipping_rate_key ) {
foreach ( $rates as $rate_key => $rate ) {
if ( $rate_key !== $free_shipping_rate_key ) {
unset( $rates[ $rate_key ] );
}
}
}
return $rates;
}
@eduande
Copy link

eduande commented Jul 13, 2020

Hello, is there any possibility that other types of shipping will also be displayed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment