WooCommerce 3中:含特定shipping class商品时仅保留local pick up的代码需求
WooCommerce 3+ Solution: Hide All Shipping Methods Except Local Pickup When Cart Contains Specific Shipping Class
Hey there, I get it—those old snippets floating around don't play nice with WooCommerce 3 and above because the platform updated how shipping rates are handled. Let's fix that with a modern, compatible solution.
Here's the code you need, tailored for WooCommerce 3+:
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods_except_local_pickup_for_specific_shipping_class', 10, 2 ); function hide_shipping_methods_except_local_pickup_for_specific_shipping_class( $rates, $package ) { // Define your target shipping class slug (replace with your actual slug) $target_shipping_class = 'only-pickup'; $has_target_class = false; // Check if any item in the cart belongs to the target shipping class foreach( $package['contents'] as $item ) { if( $item['data']->get_shipping_class() === $target_shipping_class ) { $has_target_class = true; break; // No need to check further once we find a match } } // If target class is present, hide all shipping methods except Local Pickup if( $has_target_class ) { foreach( $rates as $rate_key => $rate ) { // Keep only Local Pickup (adjust the method ID if your Local Pickup has a different ID) if( $rate->method_id !== 'local_pickup' ) { unset( $rates[$rate_key] ); } } } return $rates; }
Key Notes to Make This Work:
- Replace the shipping class slug: Swap
'only-pickup'with the actual slug of your "Only pickup" shipping class. You can find this slug in WooCommerce → Settings → Shipping → Shipping Classes (look under the "Slug" column). - Check Local Pickup method ID: Most of the time, Local Pickup uses
local_pickupas the method ID, but if you're using a custom Local Pickup extension, you might need to adjust this. You can find the method ID by inspecting the checkout page's HTML for shipping method options, or enabling WooCommerce debug mode temporarily. - Clear WooCommerce cache: After adding this code, go to WooCommerce → Status → Tools → Clear transients and Clear shipping cache. This ensures the new rules take effect immediately.
- Where to add the code: Put this in your child theme's
functions.phpfile, or use a plugin like Code Snippets to add custom code safely (avoid editing your parent theme directly—you'll lose changes when the theme updates).
This code works with WooCommerce 3.0+ because it uses the woocommerce_package_rates filter, which is the official, supported way to modify shipping rates in modern WooCommerce versions. It checks each cart package (relevant if you're using multi-shipping) and only hides methods when the target shipping class is present.
内容的提问来源于stack exchange,提问作者Guy Iusim
相关产品推荐
相关产品推荐

