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

How to Enable ‘Ship to Different Address’ with Free Shipping and Flat Rate in WooCommerce?

WooCommerce provides three default options to manage the ‘Ship to a different address’ checkbox. Out of the box, you can choose to have it checked, unchecked, or even remove the shipping form checkbox entirely. While WooCommerce only allows you to set it as checked or unchecked by default in the settings, you can also utilize code snippets to make it checked conditionally based on the selected shipping methods. This is how you can configure to check the ‘Ship to a different address’ option in WooCommerce settings.

To check the checkbox of shipping form by default

WooCommerce–> Settings-> Shipping-> Shipping Options–> Select Default to the customer shipping address.

How to Enable 'Ship to Different Address' with Free Shipping and Flat Rate in WooCommerce? - Tyche Softwares

Let’s come to the point. Based on your shipping requirements you may want to ensure that the shipping form is immediately visible to customers when the particular shipping method is chosen during the checkout process.

This post guides you well to enable the checkbox “ship to different address” checked when using Free Shipping and Flat Rate.

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.

Solution: Enable ‘Ship to Different Address’ with Free Shipping and Flat Rate in WooCommerce

Imagine an online store that allows customers to specify different billing and shipping addresses. Let’s consider that your store offers various shipping methods, including ‘Flat Rate,’ ‘Local Pickup,’ and ‘Free Shipping.’ Depending on the selected shipping method, the code assists in dynamically checking the checkbox and displaying the relevant shipping form fields for collecting shipping information.

The following code helps enable the shipping form checkbox when either ‘Flat Rate’ or ‘Free Shipping’ is selected.

Read More: How to configure Flat Rate, Free Shipping, and Table Rate Shipping in WooCommerce
// Auto Show hide checkout shipping fields based on chosen shipping methods
add_action( 'wp_footer', 'ts_checkout_field_script' );
function ts_checkout_field_script() {
    // Only on checkout page
    if( is_checkout() && ! is_wc_endpoint_url() ):

    // Get shipping methods rates data
    $rates = WC()->session->get('shipping_for_package_0')['rates'];
    $sdata  = []; // Initializing an empty array

    // Loop through shipping methods
    foreach( $rates as $rate ){
        // Targeting only "Flat rate" and "free shipping" shipping methods
        if ( in_array( $rate->method_id, ['flat_rate', 'free_shipping'] ) ) {
            // Add those shipping methods rate Ids in the array
            $sdata[] = $rate->id; 
        } 
    }

    // Jquery code start
    ?>
    <script>
        jQuery(function($){
            var a = 'input[name^="shipping_method"]',               b = a+':checked',
                c = 'input#ship-to-different-address-checkbox',
                d = <?php echo json_encode( $sdata ); ?>;

            // Conditional function that checks if the chosen shipping method enables "shipping fields"
            function rateIdEnableCheckbox( rateID, d ) {
                var e = false;

                // Loop through all available shipping methods Ids
                $.each( d, function( k, v ){
                    if( rateID == v ){
                        e = true;
                    }
                });

                return e;
            }

            // function that show or hide shipping address fields (checkbox)
            function showHideShippingAddressFields( b, c, d ) {
                var f = $(c).prop("checked") ? true : false,
                    g = rateIdEnableCheckbox( $(b).val(), d );

                if ( ( g && ! f ) || ( ! g && f ) ) {
                    $(c).click(); // Clik the checkbox (show hide shipping address)
                }
                // console.log($(b).val());
            }

            // 1. On load, the chosen shipping method
            setTimeout(function(){
                showHideShippingAddressFields( b, c, d );
            }, 100);

            // 2. On change shipping method (Live event)
            $( 'form.checkout' ).on( 'change', a, function() {
                showHideShippingAddressFields( b, c, d );
            });
        });
    </script>
    <?php
    endif;
}

Output

The output below demonstrates that when the ‘Flat Rate’ shipping method is selected, the shipping form will be checked, and it will also display the corresponding shipping fields.

How to Enable 'Ship to Different Address' with Free Shipping and Flat Rate in WooCommerce? - Tyche Softwares

Similarly, if the ‘Free Shipping’ method is selected, the checkbox is checked, and the shipping fields are also displayed.

How to Enable 'Ship to Different Address' with Free Shipping and Flat Rate in WooCommerce? - Tyche Softwares

But in the case of the ‘Local Pickup’ shipping method being chosen, it will neither check the checkbox nor show the shipping fields.

How to Enable 'Ship to Different Address' with Free Shipping and Flat Rate in WooCommerce? - Tyche Softwares

Code Explanation

  1. The function named ts_checkout_field_script, which is hooked to the WordPress footer using the add_action function. It executes when the WordPress footer is generated.
  2. The function ts_checkout_field_script begins with the conditional check to ensure it only runs on the WooCommerce checkout page.
  3. The code retrieves shipping rates data from the WooCommerce session for a specific package (package 0) and initializes an empty array named $sdata to store shipping method rate IDs.
  4. A foreach loop is employed to iterate through the available shipping rates.
  5. Within the loop, the code checks whether the shipping method matches predefined criteria, specifically, “Flat Rate” or “Free Shipping.
  6. If the shipping method meets the criteria, its rate ID is added to the $sdata array.
  7. The code switches from PHP to jQuery by starting an inline JavaScript script block.
  8. A jQuery document-ready function ensures that the code runs once the document is fully loaded.
  9. Several variables are defined within this section, including selectors for different elements, such as the shipping method radio buttons, the “ship-to-different-address” checkbox, and a JavaScript variable containing the JSON-encoded $sdata array.
  10. A JavaScript function, rateIdEnableCheckbox, is defined. It checks whether the chosen shipping method enables the display of “shipping fields” based on the selected rate ID and the provided array d.
  11. The function initializes a variable e as false and then iterates through all available shipping method IDs within the array d. If a match is found with the provided rateID, e is set to true, and the function returns e.
  12. Within this function:function showHideShippingAddressFields 
  • It determines whether the “ship-to-different-address” checkbox (c) is checked and sets a variable f to true if it is, or false if it isn’t.
  • It checks whether the currently selected shipping method (b) enables the shipping fields by invoking the rateIdEnableCheckbox function with the current shipping method and the array d.
  • Depending on the conditions, it either clicks the “ship-to-different-address” checkbox (showing or hiding the shipping address fields) or leaves it as is.

13. To ensure that the functionality works when the page initially loads, a setTimeout is employed to call the showHideShippingAddressFields function with the appropriate parameters after a brief delay.

14. An event listener for changes in the selected shipping method within the checkout form. When the shipping method is changed, it triggers the showHideShippingAddressFields function.

Conclusion

The above code snippet will either check or uncheck the checkbox of the shipping form based on the chosen shipping method. Alternatively, you can also hide the WooCommerce shipping fields when the ‘Local Pickup’ shipping method is selected.

Let us know how the code was useful or any other queries in the comments.

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