3

I would like to hide other shipping options when free shipping is available on Woocommerce.

Because latest version of woocommerce now is still showing other shipping options even if there's FREE shipping option.

Please help

Zoe
  • 27,060
  • 21
  • 118
  • 148
Luigi Vibal
  • 643
  • 2
  • 10
  • 14

1 Answers1

13

There is this recent code snippet for WooCommerce 2.6+. that you can Use:

add_filter( 'woocommerce_package_rates', 'hide_other_shipping_when_free_is_available', 100, 2 );

function hide_other_shipping_when_free_is_available( $rates, $package ) {

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}

You will need to refresh shipping cached data: disable, save and enable, save related shipping methods for the current shipping zone, in woocommerce shipping settings.


For WooCommerce 2.5, You should try this:

add_filter( 'woocommerce_package_rates', 'hide_shipping_when_free_is_available', 10, 2 );

function hide_shipping_when_free_is_available( $rates, $package ) {
    
    // Only modify rates if free_shipping is present
    if ( isset( $rates['free_shipping'] ) ) {
    
        // To unset a single rate/method, do the following. This example unsets flat_rate shipping
        unset( $rates['flat_rate'] );
        
        // To unset all methods except for free_shipping, do the following
        $free_shipping          = $rates['free_shipping'];
        $rates                  = array();
        $rates['free_shipping'] = $free_shipping;
    }
    
    return $rates;
}

Paste this code in the function.php file located in your active child theme or theme.


Reference: Hide other shipping methods when FREE SHIPPING is available (official doc)

Related:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • where shall i call this function? – Luigi Vibal Jul 09 '16 at 12:05
  • i will call this function like this add_filter( 'woocommerce_package_rates', 'my_hide_shipping_when_free_is_available', 100 ); on function.php? @LoicTheAztec – Luigi Vibal Jul 09 '16 at 13:16
  • You dont need to call it… just paste all the snippet in the function.php file of your active theme… This will do the job itself. Why? Because this function is hooked with `woocommerce_package_rates` in woocommerce core… **SEE THIS: [Hooks: Action and Filter reference](https://docs.woothemes.com/document/hooks/)** – LoicTheAztec Jul 09 '16 at 13:20
  • Would recommend turning this into a plugin or a [site specific snippets plugin](http://ottopress.com/2011/creating-a-site-specific-snippets-plugin/) so it doesn't get tied to a theme. But this is definitely the WC2.6 code since it's what the Woo developers are advising in their [gist](https://gist.github.com/claudiosmweb/943f95a022ae699c6174d22f5e32a2b1) – helgatheviking Jul 09 '16 at 23:46