EHops
EHops

Reputation: 47

Hide specific shipping method when Free Shipping is available in WooCommerce

I can find plenty of code snippets to hide other shipping options when free shipping available, or hide everything except Local Pickup. I want to hide everything except Local Pickup and a rate I set for Upgraded delivery (or in other words I want to only hide the Standard Delivery option). I have messed around with a few bits of code I found but cant get it working.

Below is one example of code I found on Github that hides everything except free shipping and collection, and I know the shipping method ID I want to also show, but cant seem to implement it.

function hide_shipping_when_free_is_available( $rates, $package ) {
    $new_rates = array();
    foreach ( $rates as $rate_id => $rate ) {
        // Only modify rates if free_shipping is present.
        if ( 'free_shipping' === $rate->method_id ) {
            $new_rates[ $rate_id ] = $rate;
            break;
        }
    }

    if ( ! empty( $new_rates ) ) {
        //Save local pickup if it's present.
        foreach ( $rates as $rate_id => $rate ) {
            if ('local_pickup' === $rate->method_id ) {
                $new_rates[ $rate_id ] = $rate;
                break;
            }
        }
        return $new_rates;
    }

    return $rates;
}

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

Upvotes: 0

Views: 410

Answers (1)

george91
george91

Reputation: 1

I know this is a late answer and you might have found a solution but you can do it like so:

    $new_rates = array();
    foreach ( $rates as $rate_id => $rate ) {
        // Only modify rates if free_shipping is present.
        if ( 'free_shipping' === $rate->method_id ) {
            $new_rates[ $rate_id ] = $rate;
            break;
        }
    }

    if ( ! empty( $new_rates ) ) {
        //Save local pickup if it's present.
        foreach ( $rates as $rate_id => $rate ) {
            if ('local_pickup' !== $rate->method_id && 'your_shipping_method_id' !== $rate->method_id ) {
                $new_rates[ $rate_id ] = $rate;
            }
        }
        return $new_rates;
    }

    return $rates;
}

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

Upvotes: 0

Related Questions