The system filters out all other shipping rates, allowing only Autoship Free Shipping under specific conditions in WooCommerce. This solution is perfect for those who provide complimentary shipping for subscriptions and want to prevent the display of redundant free shipping methods or other shipping methods during the checkout process.
Important: Always test customizations to your site on a staging environment before making changes to your live / production site.
/**
* Filters shipping rates to allow only Autoship Free Shipping based on specific conditions.
*
* This function ensures that free shipping is available only if the cart contains at least one item
* with an autoship frequency of 1, 2, 3, 4, or 5 and a frequency type of "Months".
*
* @param array $rates Array of shipping rates found for the package.
* @return array Filtered shipping rates.
*/
function xx_allow_only_autoship_free_shipping( $rates ) {
// Get the WooCommerce cart instance.
$cart = WC()->cart;
// Exit early if the cart is empty.
if ( empty( $cart ) ) {
return $rates;
}
// Flag to determine if the cart qualifies for Autoship Free Shipping.
$qualifies_for_free_shipping = false;
// Loop through cart items to check if they meet the Autoship Free Shipping requirements.
foreach ( $cart->get_cart() as $item ) {
if (
isset( $item['autoship_frequency'], $item['autoship_frequency_type'] ) &&
in_array( $item['autoship_frequency'], [1, 2, 3, 4, 5] ) && // Frequency must be 1, 2, 3, 4, or 5.
$item['autoship_frequency_type'] === 'Months'
) {
$qualifies_for_free_shipping = true;
break; // Exit loop as soon as one qualifying item is found.
}
}
// If the cart qualifies, filter out all non-Autoship Free Shipping rates.
if ( $qualifies_for_free_shipping ) {
foreach ( $rates as $rate_id => $rate ) {
if ( 'autoship_free_shipping' !== $rate->method_id ) {
unset( $rates[ $rate_id ] );
}
}
} else {
// If the cart doesn't qualify, remove Autoship Free Shipping.
foreach ( $rates as $rate_id => $rate ) {
if ( 'autoship_free_shipping' === $rate->method_id ) {
unset( $rates[ $rate_id ] );
break;
}
}
}
return $rates;
}
add_filter( 'woocommerce_package_rates', 'xx_allow_only_autoship_free_shipping', 101, 1 );