You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce限制用户每年仅购一次的代码修复请求

问题分析与修复方案

原代码的核心问题是错误使用了一年中的天数(z格式)来计算订单间隔,完全忽略了跨年场景:
比如用户去年12月31日创建的订单,z值为364;今年1月1日的z值为0,计算出的days_passed会是负数,必然小于365,导致系统误判用户仍在限制期内,无法下单。

正确的做法是通过时间戳计算两个日期的实际天数差,彻底规避跨年逻辑漏洞,修改后的代码如下:

function new_order_allowed() {
    if( ! ( is_cart() || is_checkout() ) ) return;

    if ( is_user_logged_in() ) {
        $user_id = get_current_user_id();

        $last_order = wc_get_customer_last_order( $user_id );

        if ( $last_order ) {
            // 获取订单创建时间的UTC时间戳
            $order_timestamp = $last_order->get_date_created()->getTimestamp();
            // 获取当前UTC时间戳
            $current_timestamp = current_time( 'timestamp', true );
            
            // 计算两个日期的完整天数差
            $days_passed = floor( ( $current_timestamp - $order_timestamp ) / DAY_IN_SECONDS );
            $year_in_day = 365;

            if ( $days_passed < $year_in_day ) {
               wc_add_notice( sprintf( '<b>ONLY ONE PURCHASE IS ALLOWED WITHIN 365 DAYS. </b><br>Your last order was %1$s days ago. Please try again when the 365 day period has been reached. ',  $days_passed ), 'error' );

                remove_action( 'woocommerce_proceed_to_checkout','woocommerce_button_proceed_to_checkout', 20);
            }
        }
    }
}
add_action( 'woocommerce_check_cart_items', 'new_order_allowed' );

修改说明

  • 改用时间戳计算:通过getTimestamp()获取订单创建时间的UTC时间戳,结合当前UTC时间戳,确保跨时区场景下的计算一致性
  • 使用WordPress内置常量DAY_IN_SECONDS:替代硬编码的86400,代码可读性更高
  • 用floor()取整:确保得到的是完整的天数差,避免小数导致的判断误差

内容的提问来源于stack exchange,提问作者Nat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:27:46