Mastering WooCommerce Shipping Rules: How to Hide Additional Options for Free Shipping
Website Editing Technical Support
Author: Leo MA
19/11/2023
In the world of e-commerce, setting up flexible and enticing shipping rules is crucial to enhancing the customer experience. WooCommerce, a widely-used WordPress plugin, provides a robust platform for online store owners to customize their shipping options. However, when dealing with multiple shipping rules, such as offering free shipping on orders over a certain amount while charging a fixed fee for orders below that threshold, users often face the challenge of unwanted shipping choices appearing at checkout. In this blog post, we’ll guide you through a solution to hide unnecessary shipping options when free shipping is available, using a simple snippet of PHP code.
The Challenge: By default, WooCommerce displays all available shipping options at checkout, even when the conditions for free shipping are met. This can lead to confusion for customers and potentially impact the overall shopping experience. To address this issue, we can leverage a snippet of PHP code to hide non-essential shipping choices when free shipping is applicable.
The Solution: To implement this solution, you need to add the following PHP code to your WordPress theme’s functions.php file:
/**
* Hide shipping rates when free shipping is available.
*
* @param array $rates Array of rates found for the package.
* @return array
*/
function my_hide_shipping_when_free_is_available( $rates ) {
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id ) {
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
add_filter( 'woocommerce_package_rates',
'my_hide_shipping_when_free_is_available', 100 );
Explanation: This code defines a custom function (my_hide_shipping_when_free_is_available
) that filters the available shipping rates. It checks if free shipping is among the options and, if so, retains only the free shipping option while removing others. The add_filter
function hooks this custom function into the WooCommerce shipping rates calculation process.
Implementation:
- Access your WordPress admin panel.
- Navigate to the “Appearance” section and select “Theme Editor.”
- Open the “functions.php” file for editing.
- Copy and paste the provided PHP code at the end of the file.
- Save the changes.
By incorporating this PHP code into your WooCommerce setup, you can streamline the checkout process for your customers, ensuring that only relevant shipping options are displayed. This enhancement contributes to a smoother and more user-friendly shopping experience, ultimately benefiting both you and your customers. Happy selling!