Hide Shipping Methods When Free Shipping is Available
Explanation
When you're shopping online, it's always nice to get free shipping, right? This little piece of code helps make sure that when free shipping is available in your WooCommerce store, all the other shipping options disappear. Here's how it works:
- Checks for Free Shipping: The code looks through all the shipping options available for a purchase.
- Finds Free Shipping: If it finds a free shipping option, it keeps that one and ignores the rest.
- Hides Other Options: Once free shipping is found, it stops looking and hides all other shipping methods.
This way, your customers won't be confused by multiple shipping choices when they can get their items shipped for free. It's a neat trick to streamline the checkout process and make sure everyone gets the best deal!
Code
<?php
/**
* Hide all other shipping methods when free shipping is available.
*
* This function checks if free shipping is available and hides all other shipping methods.
*
* @param array $rates Array of available shipping rates.
* @return array Modified array of shipping rates.
*/
function wp_dudecom_hide_shipping_when_free_is_available( $rates ) {
$free = array();
// Loop through the available shipping rates
foreach ( $rates as $rate_id => $rate ) {
// Check if the shipping method is free shipping
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
break; // Exit loop once free shipping is found
}
}
// Return free shipping if available, otherwise return all rates
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates', 'wp_dudecom_hide_shipping_when_free_is_available', 100 );
?>
Instructions
To implement the functionality of hiding all other shipping methods when free shipping is available in your WooCommerce store, follow these steps:
File Location: Add the code to your theme's functions.php
file or a custom plugin file.
Prerequisites:
- Ensure WooCommerce is installed and activated on your WordPress site.
- Have access to edit theme files or create a custom plugin.
Implementation Steps:
- Log in to your WordPress admin dashboard.
- Navigate to Appearance > Theme Editor if you are editing the
functions.php
file, or go to Plugins > Editor if you are adding the code to a custom plugin. - Locate the
functions.php
file of your active theme or the file of your custom plugin. - Copy the provided code snippet.
- Paste the code into the
functions.php
file or your custom plugin file. - Save the changes.
- Test the checkout process on your WooCommerce store to ensure that when free shipping is available, other shipping methods are hidden.
If you need assistance with this implementation or require more advanced functionality, consider reaching out to wp-dude.com for expert help.