Home > database >  Hide shipping methods based on availability of other shipping methods in WooCommerce
Hide shipping methods based on availability of other shipping methods in WooCommerce

Time:10-22

I am trying to hide shipping methods based on the availability of other shipping methods (by their IDs), for a somewhat complex shipping setup.

Based on other code snippets I've found (for other use cases, excluding states or only showing free shipping if available), I came up with this:

function hide_duplicate_shipping_methods ( $rates ) {
  
  foreach ( $rates as $rate_id => $rate ) {
    
    if ( 'flat_rate:10' === $rate->method_id ) {
        unset( $rates['flat_rate:28'] );
    }
  }
  return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_duplicate_shipping_methods', 100 );

However, this doesn't hide anything and I really can't find or think of anything else.

Any advice?

CodePudding user response:

  • $rate->method_id will be equal to local_pickup, free_shipping, flat_rate, etc..

  • while $rate_id will be equal to local_pickup:1, free_shipping:2, etc..

So either you use it like this:

function filter_woocommerce_package_rates( $rates, $package ) { 
    // Loop trough
    foreach ( $rates as $rate_id => $rate ) {
        // Checks if a value exists in an array, multiple can be added, separated by a comma
        if ( in_array( $rate->method_id, array( 'local_pickup', 'free_shipping' ) ) ) {
            unset( $rates['flat_rate:28'] );
        }
    }   
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

OR like this:

function filter_woocommerce_package_rates( $rates, $package ) { 
    // Loop trough
    foreach ( $rates as $rate_id => $rate ) {
        // Checks if a value exists in an array, multiple can be added, separated by a comma
        if ( in_array( $rate_id, array( 'local_pickup:1', 'free_shipping:2' ) ) ) {
            unset( $rates['flat_rate:28'] );
        }
    }   
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

Code goes in functions.php file of the active child theme (or active theme). Tested and works in Wordpress 5.8.1 & WooCommerce 5.8.0

Don't forget to empty your cart to refresh shipping cached data.

  • Related