phpwordpresswoocommercehook-woocommerceshipping-method

Hide other shipping methods if specific one is present in WooCommerce


I'm trying to hide all other shipping methods conditionally if a specific one is present.

Here is my code:

function hide_shipping_when_alg_wc_shipping_31_is_present( $rates, $package ) {
    // Check if alg_wc_shipping:31 is present
    $alg_wc_shipping_31_present = false;
    foreach ( $package->get_shipping_items() as $item ) {
        if ( $item->needs_shipping() && $item->get_shipping_class() === 'alg_wc_shipping:31' ) {
            $alg_wc_shipping_31_present = true;
            break;
        }
    }

    // If alg_wc_shipping:31 is present, hide alg_wc_shipping:30 and alg_wc_shipping:29
    if ( $alg_wc_shipping_31_present ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( in_array( $rate->get_method_id(), array( 'alg_wc_shipping:30', 'alg_wc_shipping:29' ) ) ) {
                unset( $rates[ $rate_key ] );
            }
        }
    }
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_alg_wc_shipping_31_is_present', 10, 2 );

But it's not working. Can somebody tell me what is wrong with this code?

I tried several things, and it didn't work at all.


Solution

  • Your code can really be simplified to hide other shipping methods if specific shipping method is available:

    add_filter( 'woocommerce_package_rates', 'hide_others_except_specific_shipping_method', 10, 2 );
    function hide_others_except_specific_shipping_method( $rates, $package ) {
        // Define the specific shipping method to keep if present
        $targeted_method_rate_id = 'alg_wc_shipping:31';
    
        if ( isset($rates[$targeted_method_rate_id]) ) {
            return array( $targeted_method_rate_id => $rates[$targeted_method_rate_id] );
        }
        return $rates;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Important: You will have to empty your cart to refresh shipping methods cache.