如何移除WooCommerce自定义配送插件默认实例,仅保留区域配送?
Hey there! I’ve run into this exact issue before when building custom WooCommerce shipping methods—those default global instances popping up in the top submenu can be annoying. Let’s get rid of it so only your zone-specific instances show up.
Why This Happens
When you extend WooCommerce’s WC_Shipping_Method class to build your custom plugin, WooCommerce automatically creates a global instance (with an instance_id of 0) for your shipping method by default. This is what’s showing up as "UK Flat Rate" in the top settings submenu.
Solution 1: Filter Out the Global Instance
Add this code snippet to your plugin’s main file (or your child theme’s functions.php if you’re testing):
add_filter( 'woocommerce_get_shipping_methods', 'remove_default_custom_shipping_instance', 10, 1 ); function remove_default_custom_shipping_instance( $methods ) { // Replace 'your_custom_shipping_id' with the actual ID of your shipping method $custom_shipping_id = 'your_custom_shipping_id'; if ( isset( $methods[$custom_shipping_id] ) && isset( $methods[$custom_shipping_id]['0'] ) ) { // Unset the global instance (instance ID 0) unset( $methods[$custom_shipping_id]['0'] ); } return $methods; }
This hook targets the list of registered shipping methods and removes the global instance (marked with ID 0) for your custom method.
Solution 2: Disable Global Instance in Your Shipping Class
If you want to prevent the global instance from being created in the first place, tweak your custom shipping method’s constructor:
class WC_Custom_UK_Flat_Rate extends WC_Shipping_Method { public function __construct( $instance_id = 0 ) { // Skip loading if this is the global instance (no instance ID) if ( $instance_id === 0 ) { return; } parent::__construct( $instance_id ); // Your existing setup code $this->id = 'your_custom_shipping_id'; $this->method_title = __( 'UK Flat Rate', 'your-plugin-text-domain' ); $this->method_description = __( 'Custom flat rate with extra fields', 'your-plugin-text-domain' ); $this->supports = array( 'shipping-zones', 'instance-settings', // Add other supports your plugin needs ); // Load your settings $this->init(); } // Rest of your class methods (init, calculate_shipping, etc.) }
By checking if $instance_id is 0 at the start of the constructor, you prevent the global instance from initializing entirely.
Important Notes
- Replace
your_custom_shipping_idwith the actual ID you assigned to your shipping method in the class. - If you’re using a text domain for translations, update
your-plugin-text-domainto match your plugin’s domain. - Always test code changes on a staging site first to avoid breaking your live store.
After adding either of these fixes, refresh your WooCommerce shipping settings page—the default "UK Flat Rate" instance in the top submenu should be gone, and only the instances you added to the UK shipping zone will appear.
内容的提问来源于stack exchange,提问作者TheLearningDev

