Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active July 15, 2021 13:47
Show Gist options
  • Save jorpdesigns/b2490852fd8833ad58fbab19af5e79fb to your computer and use it in GitHub Desktop.
Save jorpdesigns/b2490852fd8833ad58fbab19af5e79fb to your computer and use it in GitHub Desktop.
Snippet to hide WooCommerce shipping rates if free shipping is available
<?php
// ONLY SHOW FREE SHIPPING METHOD IF AVAILABLE
add_filter( 'woocommerce_package_rates', 'only_show_free_shipping', 100 );
function only_show_free_shipping( $rates ) {
$free_rates = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free_rates[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free_rates ) ? $free_rates : $rates;
}
// SHOW FREE SHIPPING METHODS AS WELL AS LOCAL PICKUP AND ZERO FLAT RATES
add_filter( 'woocommerce_package_rates', 'custom_hide_all_shipping_when_free_is_available' );
function custom_hide_all_shipping_when_free_is_available( $shipping_rates) {
$free_rates = array();
$free_shipping_available = false;
foreach ( $shipping_rates as $key => $rate ) {
if ( 0 == $rate->cost) {
$free_shipping_available = true;
$free_rates[ $key ] = $rate;
}
}
if ( $free_shipping_available ) {
return $free_rates;
}
return $shipping_rates;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment