How to hide specific shipping methods in WooCommerce based on cart subtotal?

To hide specific shipping methods in WooCommerce based on the cart subtotal, you can use a custom code snippet. This snippet will hook into the WooCommerce shipping method filter and conditionally exclude the shipping methods you want to hide based on the cart subtotal. Here's a step-by-step guide on how to achieve this:

Step 1: Add the custom code snippet

Add the following code to your theme's functions.php file or a custom plugin file:

add_filter('woocommerce_package_rates', 'codefynd_hide_shipping_methods_based_on_subtotal', 10, 2);
function codefynd_hide_shipping_methods_based_on_subtotal($rates, $package)
{
    // Define the cart subtotal threshold to hide shipping methods (change this value as needed)
    $subtotal_threshold = 100;

    // Get the cart subtotal
    $cart_subtotal = WC()->cart->subtotal;

    // Check if the cart subtotal is greater than or equal to the threshold
    if ($cart_subtotal >= $subtotal_threshold) {
        // Shipping method IDs to hide (you can add more method IDs to this array)
        $shipping_methods_to_hide = array(
            'flat_rate:1', // Replace 'flat_rate:1' with the actual method ID you want to hide
            'free_shipping:2', // Replace 'free_shipping:2' with the actual method ID you want to hide
        );

        // Loop through the shipping methods and unset the ones to hide
        foreach ($shipping_methods_to_hide as $method_id) {
            if (isset($rates[$method_id])) {
                unset($rates[$method_id]);
            }
        }
    }

    return $rates;
}

Step 2: Customize the code

In the code snippet above, you can customize the $subtotal_threshold variable to set the minimum cart subtotal amount required to hide the specified shipping methods. Change the value of $subtotal_threshold to your desired amount.

Also, modify the $shipping_methods_to_hide array to include the shipping method IDs you want to hide. You can find the method IDs in the WooCommerce settings under WooCommerce > Settings > Shipping > Shipping Zones > Edit the desired shipping method.

Step 3: Save changes and test

Once you've added the custom code snippet, save the changes to your theme's functions.php file or custom plugin file. Test your WooCommerce cart with different cart subtotal amounts to ensure that the specified shipping methods are hidden when the cart subtotal exceeds the threshold.

Please note that this code snippet assumes that you are using the standard WooCommerce shipping methods such as "Flat Rate" and "Free Shipping." If you have custom shipping methods, you may need to adjust the method IDs accordingly. Always make sure to test the functionality thoroughly to ensure it works as expected with your specific setup.

Muhammad Alfaiz
Alfaiz 7 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x