WooCommerce - Hide other shipping methods when FREE SHIPPING is available

前端 未结 1 1498
栀梦
栀梦 2020-11-27 23:30

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 shippin

相关标签:
1条回答
  • 2020-11-28 00:27

    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)
    • WooCommerce Free Shipping if over 5 pounds
    0 讨论(0)
提交回复
热议问题