问题描述
基于Hide specific shipping method depending on day time in WooCommerce的答案代码,我希望仅允许星期一至星期五下午3点之前。
//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;
}
解决方法
您将使用带有date()
参数的N
函数来处理星期几,使用H
参数来处理小时数,如下所述,以在周末和3点以后禁用特定的送货方式工作日下午:
// 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;
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。
清除运输缓存:
- 您将需要清空购物车,以清除缓存的运输数据
- 或者在运输设置中,您可以禁用/保存任何运输方式,然后启用回退/保存。