'Disable a woocommerce delivery method on weekends and cut off time in the week

Based on Hide specific shipping method depending on day time in WooCommerce answer code, I am looking to only allow Monday to Friday before 3pm.

//hide shipping method based on time
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_time', 10, 2 );
function hide_shipping_method_based_on_time( $rates, $package )
{
    // Set your default time zone (http://php.net/manual/en/timezones.php)
    date_default_timezone_set('Europe/London');
    
    // Here set your shipping rate Id
    $shipping_rate_id = 'flat_rate:29';

    // When this shipping method is available and after 2 PM
    if ( array_key_exists( $shipping_rate_id, $rates ) && date('H') > 14 ) {
        unset($rates[$shipping_rate_id]); // remove it
    }
    return $rates;

}


Solution 1:[1]

You will use the date() function with N parameter to handle the day of the week and H parameter to handle hours as follow to disable a specific shipping method on weekends and after 3 PM the weekdays:

// Hide shipping method based on the day of the week and time
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_day_of_the_week_and_time', 10, 2 );
function hide_shipping_method_based_on_day_of_the_week_and_time( $rates, $package )
{
    // Set your default time zone (http://php.net/manual/en/timezones.php)
    date_default_timezone_set('Europe/London');
    
    // Here set your shipping rate Id
    $shipping_rate_id = 'flat_rate:29';

    // When this shipping method is available and after 2 PM
    if ( array_key_exists( $shipping_rate_id, $rates ) 
    && ! ( date('H') <= 15 && ! in_array(date('N'), [6,7]) ) ) {
        unset($rates[$shipping_rate_id]); // remove it
    }
    return $rates;
}

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

Clearing shipping caches:

  • You will need to empty your cart, to clear cached shipping data
  • Or In shipping settings, you can disable / save any shipping method, then enable back / save.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 LoicTheAztec