Ecommerce Shopify WordPress Discussion

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.
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.

February 17, 2024

TurboCommerce make the better internet purchasing globaly

Turbo Multi-language Translator

Make the better internet purchasing globaly

Turbosify SEO Speed Booster

5.0 (7) Free plan available
Get better conversions by improving store loading speed Installed

Turbo Multi-language Chat - AI Customer service in one hand

TurboCommerce make the better internet purchasing globaly
Our products

The help you need, when you need it

App by Turbo Engine

3 apps • 5.0 average rating

Turbosify Speed Booster

5.0 (7)
Get better conversions by optimizing shopify store Google page speed Installed

Turbosify Translator for Wordpress Woocommerce

5.0 (74) Free Wordpress Woocommerce Plugin
Translate your wordpress website to multiple language within 1 click, no configuration needed, no No technical required

Grow your business here

Whether you want to sell products down the street or around the world, we have all the tools you need.