Search code examples
phpwordpressdatewoocommerceshipping-method

Disable free shipping until a specific date in WooCommerce


I want to disable free shipping until a certain date in WooCommerce using PHP only.

add_filter( 'woocommerce_package_rates', 'disable_free_shipping_until_certain_date', 10, 2 );

function disable_free_shipping_until_certain_date($rates, $package) {
    $current_date = date("Y-m-d");
    $disable_date = strtotime('2024-02-25');
    $disable_date = date('Y-m-d',$disable_date);
    
    if($current_date < $disable_date){
        unset( $rates['free_shipping'] );
    }
    return $rates;
}

This is the PHP snippet I made, but it doesn't work.
Why I can't make it work?
What do I need to change?


Solution

  • You need to define the correct shipping rate ID (array key) for your free shipping method in the current shipping zone, to make it work in your code.

    Try the following, to disable free shipping until a specific defined date threshold:

    add_filter( 'woocommerce_package_rates', 'disable_free_shipping_until_specific_date', 10, 2 );
    function disable_free_shipping_until_specific_date( $rates, $package ) {
        $threshold_date = '2024-02-25'; // Threshold date until free shipping is disabled
    
        // Loop through shipping rates for the current shipping package
        foreach ( $rates as $rate_key => $rate ) {
            // Targeting free shipping and specific date
            if ( 'free_shipping' === $rate->method_id && time() <= strtotime($threshold_date) ) {
                unset($rates[$rate_key]); // Remove shipping rate
            }
        }
        return $rates;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Important: You will have to empty your cart to refresh shipping method cache.