I am using Hide specifics Flat Rates when Free Shipping is available in WooCommerce 3 lightly changed answer code to hide all shipping methods except one. The only method I want showing is a rate from the “Woocommerce Advanced Shipping” plugin.
I am using the correct rate ID etc…
Everything works fine except when a customer tries to click that shipping method, it won’t stay selected. It just jumps back to free shipping.
I have tried debugging and also tried the code with a native woocommerce flat rate ID and it showed up/able to select it just fine.
add_filter( 'woocommerce_package_rates', 'conditionally_hide_shipping_methods', 100, 2 ); function conditionally_hide_shipping_methods( $rates, $package ) { $flat_rates_express = array( '2588' ); $free = $flat2 = array(); foreach ( $rates as $rate_key => $rate ) { // Updated Here To if ( in_array( $rate->id, $flat_rates_express ) ) $flat2[ $rate_key ] = $rate; if ( 'free_shipping:12' === $rate->id ) $free[ $rate_key ] = $rate; } return ! empty( $free ) ? array_merge( $free, $flat2 ) : $rates; }
ID I want to Keep Shown: “2588” (Custom Shipping Rate From Plugin)
How can I disable the Flat rate shipping method when free shipping is available o and keep a custom shipping rate (from a plugin)?
Advertisement
Answer
As you have 3 shipping methods, 1 free shipping, 1 flat rate and 1 custom ‘2588’, it’s possible to hide the flat rate shipping method when free shipping is available instead:
add_filter( 'woocommerce_package_rates', 'free_shipping_disable_flat_rate', 1000, 2 ); function free_shipping_disable_flat_rate( $rates, $package ) { // Here your free shipping rate Id $free_shipping_rate_id = 'free_shipping:12'; // When your Free shipping method is available if ( array_key_exists( $free_shipping_rate_id, $rates ) ) { // Loop through shipping methods rates foreach ( $rates as $rate_key => $rate ) { // Removing "Flat rate" shipping method if ( 'flat_rate' === $rate->method_id ){ unset($rates[$rate_key]); } } } return $rates; }
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Refresh the shipping caches:
- This code is already saved on your function.php file.
- In a shipping zone settings, disable / save any shipping method, then enable back / save.
You are done and you can test it.