WooCommerce显示13:00剩余时长功能故障排查及优化咨询
代码问题排查与优化方案
问题原因分析
原代码存在两个核心问题导致13:00及之后无输出:
- 条件判断遗漏边界值:使用
elseif (date('H') > 13),当时间恰好为13:00整时,既不满足<13也不满足>13,无法进入任何分支,导致$del_day、$hour、$min变量未定义,输出HTML时触发错误中断渲染。 - 代码冗余且逻辑不严谨:两个分支内的时间计算逻辑完全重复,增加维护成本;同时用
date()处理剩余时间戳的方式存在时区偏差风险。
修复与优化方案
- 修正条件覆盖范围:用
else替代elseif (date('H') > 13),覆盖13:00及之后的所有场景,确保所有分支都能定义必要变量。 - 抽离重复逻辑:将时间计算、剩余时长解析等重复代码提取到分支外部,减少冗余。
- 使用DateTime类:替代
strtotime和date函数,时间处理更直观健壮,避免时区和时间戳转换的潜在问题。 - 初始化变量:提前初始化所有输出变量,彻底杜绝未定义错误。
优化后的代码
add_action( 'woocommerce_after_add_to_cart_form', 'delivery_info' ); function delivery_info() { date_default_timezone_set( 'Europe/London' ); // 初始化变量,避免未定义错误 $del_day = ''; $hour = 0; $min = 0; $now = new DateTime(); $todayCutoff = new DateTime('today 13:00'); if ($now < $todayCutoff) { // 早于13:00,7个工作日后送达 $delDate = (new DateTime())->modify('7 weekdays'); $targetTime = $todayCutoff; } else { // 13:00及之后,8个工作日后送达 $delDate = (new DateTime())->modify('8 weekdays'); $targetTime = new DateTime('tomorrow 13:00'); } // 格式化送达日期 $del_day = $delDate->format('l jS F'); // 计算剩余时长 $timeInterval = $now->diff($targetTime); $hour = $timeInterval->h; $min = $timeInterval->i; // HTML输出 echo <<<HTML <br> <div class="woocommerce-message est-delivery" style="white-space: pre-line; text-align: left; display: inline-block; "> <h4>Standard Delivery</h4> <br> <span style='color:#000000'> Order arrives <b>{$del_day}</b>, </span> <br/> <span style="color:#47bab5"> order within {$hour}hrs {$min}mins </span> </div> HTML; }
优化说明
- 用
DateTime类直接比较时间($now < $todayCutoff),比字符串转时间戳的方式更直观可靠。 - 借助
DateInterval计算剩余时长,无需手动处理时间戳差值,避免时区偏差。 - 代码结构更简洁,重复逻辑被抽离,后续维护成本更低。
内容的提问来源于stack exchange,提问作者richag
相关产品推荐
相关产品推荐

