Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Set All Shipping Methods’ Cost to Zero for a Free Shipping Coupon in WooCommerce?

WooCommerce built-in functionalities help you to smartly set up shipping methods and allow free shipping to all products. But when your online store is jumping into clearance sale of certain products you may provide coupons combined with free shipping. In this case, you need to explore smart choices to change the rates of other shipping methods. 

This post helps you to set all shipping methods costs to zero for a free shipping coupon in WooCommerce.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install & activate the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

Preliminary Steps

1. Enable the free shipping method in your desired shipping zone and set the free shipping setting to require a  “A valid free shipping coupon”.The setting can be done from WooCommerce >Settings >Shipping >Shipping zones. Select & Edit a Shipping method.

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

2. Decide the specific coupon for which when applied should set the shipping costs to zero(e.g. summer).

Preliminary Steps to setting all shipping methods' cost to zero for a free shipping coupon in WooCommerce?

3. Please make sure to enable the checkbox of  “Allow free shipping” of that specific coupon. If the checkbox is not enabled then it doesn’t change the shipping costs on the frontend.

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

Solution: Set All Shipping Methods’ Cost to Zero for all Free Shipping Coupon in WooCommerce

Let’s consider that a store owner who operates an online Clothing & Accessories store wants to clear out summer collections. So the code implemented below helps to adjust shipping costs to zero when a specific coupon, such as “summer,” is applied and with the configurations done in WooCommerce coupons as above.

add_filter( 'woocommerce_package_rates', 'ts_coupon_free_shipping', 20, 2 );
function ts_coupon_free_shipping( $rates, $package ) {
    $has_free_shipping = false;
    $applied_coupons = WC()->cart->get_applied_coupons();
    foreach( $applied_coupons as $coupon_code ){
        $coupon = new WC_Coupon($coupon_code);
        if($coupon->get_free_shipping()){
            $has_free_shipping = true;
            break;
        }
    }
    foreach( $rates as $rate_key => $rate ){
        if( $has_free_shipping ){
            // For other shipping methods (not 'free_shipping')
            if( $rate->method_id !== 'free_shipping'){
                // Append rate label titles (free)
                $rates[$rate_key]->label .= ' ' . __('(free)', 'woocommerce');
                // Set rate cost
                $rates[$rate_key]->cost = 0;
                // Set taxes rate cost (if enabled)
                $taxes = array();
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $rates[$rate_key]->taxes[$key] > 0 )
                        $taxes[$key] = 0;
                }
                $rates[$rate_key]->taxes = $taxes;
            }
        }
    }
    return $rates;
}
How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

Schedule Local Deliveries & Pickups in WooCommerce

Order Delivery Date Pro for WooCommerce lets you create different delivery schedules, set charges for Weekdays & special dates, manage local pickup dates, and notify customers once the order is ready

Since the customers pick a delivery date and time set by you, order fulfillment and customer satisfaction becomes a breeze.

Output

Use case: Coupon that has enabled ‘Allow Free shipping’

In the below output, the summer coupon has been applied and hence the shipping costs are set to be zero. As we have already set the configuration of this ‘summer ‘ coupon to allow free shipping, it sets the costs of shipping methods to zero or free.

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

Use case: Coupon that has not enabled ‘Allow Free Shipping’

If any other coupons such as “flashsale” are applied the code will not change the shipping costs but instead shows the default rates configured in the shipping methods.

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

Code Explanation

Filter Registration:

  • The code begins by registering a filter in WooCommerce using add_filter.
  • The filter being used is ‘woocommerce_package_rates‘, which is a filter hook that allows modification of shipping rates.
  • The callback function that will handle this filter is ts_coupon_free_shipping.
  • Priority is set to 20, which determines the order in which filters are applied.
  • 2 is the number of arguments the callback function expects.

Callback Function Definition:

  • The ts_coupon_free_shipping function is defined with two parameters: $rates and $package.
  • $rates is an array that contains information about the available shipping rates, and $package holds information about the package being shipped.

Variable Initialization:

  • The code initializes a boolean variable $has_free_shipping and sets it to false. This variable will be used to track whether a free shipping coupon is applied.

Fetching Applied Coupons:

  • It fetches the list of applied coupons in the WooCommerce cart using $applied_coupons = WC()->cart->get_applied_coupons();.

Checking for Free Shipping Coupons:

  • A foreach loop iterates through each applied coupon code.
  • For each coupon, a WC_Coupon object is created, and the get_free_shipping() method is used to check if it offers free shipping.
  • If any coupon provides free shipping, the $has_free_shipping variable is set to true, and the loop breaks.

Modifying Shipping Rates:

  1. Another foreach loop iterates through each shipping rate in the $rates array.
  2. If $has_free_shipping is true (indicating a free shipping coupon is active), the code performs the following modifications for non-‘free_shipping’ methods:
  • Appends ‘(free)’ to the rate label to indicate that the shipping is free.
  • Sets the rate cost to 0, effectively making the shipping method free.

    3.Checks and sets the tax rate cost to 0 if taxes are enabled for the shipping method.

Returning Modified Rates:

  • Finally, the modified $rates array, reflecting the changes made to shipping methods, is returned from the function.

Solution: Set All Shipping Methods’ Cost to Zero for a Specific Coupon in WooCommerce

The above use cases work mainly based on the configuration of WooCommerce settings and the code. Also, it is applicable to all coupons that have “Allow free shipping” enabled. But if you don’t want to depend on settings and prefer using only a code snippet to set shipping costs for all shipping methods to 0 for specific coupons, this code can help.

NOTE: Refer to the coupon settings image that even though the ‘Allow Free shipping ‘ checkbox is not enabled, the code achieves to set all shipping methods to 0 cost.

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares
// Hook into WooCommerce shipping rate calculation
add_filter('woocommerce_package_rates', 'ts_specific_coupon_free_shipping', 20, 2 );

// Define the function that adjusts shipping costs for the specific coupon
function ts_specific_coupon_free_shipping( $rates, $package ) {
    $specific_coupon_code = 'winter';

    $is_specific_coupon_applied = false;

    $applied_coupons = WC()->cart->get_applied_coupons();

    if (in_array($specific_coupon_code, $applied_coupons)) {
        $is_specific_coupon_applied = true;
    }

    $is_other_coupon_applied = count($applied_coupons) > 1;

    if( $is_specific_coupon_applied && !$is_other_coupon_applied ){
        foreach( $rates as $rate_key => $rate ){
            if( $rate->method_id === 'free_shipping'){
                $rates[$rate_key]->label = $rate->label;
            }
            else {
                $rates[$rate_key]->label .= ' ' . __('(free)', 'woocommerce');
                $rates[$rate_key]->cost = 0;
                $taxes = array();
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $rates[$rate_key]->taxes[$key] > 0 )
                        $taxes[$key] = 0;
                }
                $rates[$rate_key]->taxes = $taxes;
            }
        }
    }

    return $rates;
}

Related Article: How to Disable Free Shipping Method After Applying a Coupon Code in WooCommerce?

Output

Use case: The specific coupon ‘winter’ is applied

How to Set All Shipping Methods' Cost to Zero for a Free Shipping Coupon in WooCommerce? - Tyche Softwares

Code Explanation

Step 1: Hook into WooCommerce Shipping Calculation

In the first step, we use the add_filter function to hook our custom function, ts_specific_coupon_free_shipping, into WooCommerce’s shipping rate calculation process. 

Step 2: Define the Custom Function

We define our custom function ts_specific_coupon_free_shipping. This function takes two parameters: $rates, which is an array representing shipping rates, and $package, which contains information about the package being shipped.

Step 3: Set the Target Coupon Code

We specify the coupon code we want to target. In this case, we set it to ‘winter’. This code will modify shipping rates only when this specific coupon is applied.

Step 4: Initialize Variables

We start by initializing a boolean variable, $is_specific_coupon_applied, to false. Additionally, we retrieve a list of applied coupons from the WooCommerce cart using WC()->cart->get_applied_coupons().

Step 5: Check If the Target Coupon Is Applied

Here, we check if the target coupon code (‘winter’) is among the applied coupons. If it is, we set $is_specific_coupon_applied to true, indicating that the specific coupon we’re targeting is applied.

Step 6: Check for Other Applied Coupons

We determine if any other coupons are applied by counting the number of applied coupons. If there is more than one applied coupon, we set $is_other_coupon_applied to true.

Step 7: Modify Shipping Rates

If the target coupon is applied (‘winter’) and no other coupons are applied, we enter a loop to modify each shipping rate.

Step 8: Modify Label for Free Shipping Method

For the ‘free_shipping’ method, we preserve its original label without adding ‘(free)’ to it. This ensures that free shipping remains as is.

Step 9: Modify Other Shipping Methods

For all other shipping methods, we append ‘(free)’ to their labels to indicate that they are now free of charge. We also set their cost to and ensure that any applied taxes are removed.

Step 10: Return Modified Shipping Rates

Finally, we return the modified shipping rates array, which will now reflect the changes we made based on the presence of the ‘winter’ coupon and the absence of any other coupons. 

Conclusion

The 1st code snippet above helps store owners offer free shipping on all shipping methods when customers apply any WooCommerce coupon code that has “Allow free shipping” enabled, thereby keeping regular shipping rates intact when a different coupon is used. The 2nd code snippet will achieve the same output but for a specific coupon code only. You can modify the code to apply free shipping to specific products or categories, even when a coupon is not used.

Let us know your thoughts on how the code was useful or any other queries in the comments section.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

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