WooCommerce指定日期与截止时间的特定运费方案显示代码优化需求
WooCommerce运费方案显示逻辑修正
现有运费方案
- Saturday Delivery(ID:
flat_rate:34):固定运费11.25英镑 - Saturday Delivery(ID:
flat_rate:35):订单金额≥75英镑时收取5英镑 - Free Next Day Delivery(ID:
shipping_method_0_free_shipping19):全周可用
功能需求
flat_rate:34仅在周四全天及周五12:30前显示,周五12:30后隐藏;- 订单金额≥75英镑时,显示
flat_rate:35并隐藏flat_rate:34; flat_rate:35需与Free Next Day Delivery同时显示(当前仅显示免费配送,不符合需求)。
修正后的代码
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_time', 10, 2 ); function hide_shipping_method_based_on_time( $rates, $package ) { date_default_timezone_set('Europe/London'); $threshold = 75; $shipping_rate_id_1 = 'flat_rate:34'; $shipping_rate_id_2 = 'flat_rate:35'; $free_shipping_id = 'shipping_method_0_free_shipping19'; // 记录免费配送是否存在,确保后续始终保留 $has_free_shipping = isset($rates[$free_shipping_id]); // 转换当前时间为分钟数,简化时间判断逻辑 $current_day = date('N'); // 1=周一,4=周四,5=周五,7=周日 $current_total_minutes = (int)date('H') * 60 + (int)date('i'); $friday_cutoff_minutes = 12 * 60 + 30; // 周五12:30对应的总分钟数 // 判断订单金额是否达到阈值 $is_over_threshold = WC()->cart->subtotal >= $threshold; // 处理flat_rate:34的显示规则 if (isset($rates[$shipping_rate_id_1])) { // 满足以下任一条件则隐藏:金额达标,或不在周四/周五12:30前 if ($is_over_threshold || !($current_day == 4 || ($current_day == 5 && $current_total_minutes < $friday_cutoff_minutes))) { unset($rates[$shipping_rate_id_1]); } } // 处理flat_rate:35的显示规则 if (isset($rates[$shipping_rate_id_2])) { // 仅当金额达标+时间在周四/周五12:30前时显示 if (!$is_over_threshold || !($current_day == 4 || ($current_day == 5 && $current_total_minutes < $friday_cutoff_minutes))) { unset($rates[$shipping_rate_id_2]); } } // 确保免费配送始终显示(如果原本存在) if ($has_free_shipping && !isset($rates[$free_shipping_id])) { $rates[$free_shipping_id] = $package['rates'][$free_shipping_id]; } return $rates; }
代码说明
- 时区设置:固定为欧洲伦敦时区,确保时间判断准确;
- 时间判断优化:将小时和分钟转为总分钟数,避免字符串比较的误差;
- 金额阈值整合:直接使用
WC()->cart->subtotal >= $threshold判断订单金额是否达标; - 逻辑拆分:分别对两个flat_rate的显示条件做独立判断,避免逻辑混淆;
- 免费配送保障:强制保留Free Next Day Delivery,满足与
flat_rate:35共存的需求; - 修复原代码错误:修正了
array_key_exists的误用(原代码同时传多个键,该函数仅支持单个键检查),以及时间比较的语法错误。
内容的提问来源于stack exchange,提问作者richag
相关产品推荐
相关产品推荐

