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

PHP实现WordPress用户元日期是否超两个月的正确校验

问题解决步骤

1. 首次登录日期字段的写入逻辑

用wp_login动作处理首次登录日期写入,该动作在用户登录成功后触发,能精准捕获首次登录时机:

add_action('wp_login', 'set_first_login_date', 10, 2);
function set_first_login_date($user_login, $user) {
    $first_login = get_user_meta($user->ID, 'first_login_date', true);
    if (empty($first_login)) {
        // 写入d/m/Y格式的当前日期
        $current_date = date('d/m/Y');
        update_user_meta($user->ID, 'first_login_date', $current_date);
    }
}

注册时无需额外操作,用户元字段默认为空;若需强制初始化,可添加user_register动作:

add_action('user_register', 'init_first_login_field');
function init_first_login_field($user_id) {
    add_user_meta($user_id, 'first_login_date', '', true);
}

2. 修复日期校验逻辑

直接用strtotime处理d/m/Y格式会有歧义(比如05/06/2024会被错误解析为6月5日),用PHPDateTime类可精准处理:

function is_login_date_expired($user_id) {
    $stored_date_str = get_user_meta($user_id, 'first_login_date', true);
    
    // 字段为空则标记为需处理
    if (empty($stored_date_str)) {
        return true;
    }
    
    // 解析存储的d/m/Y格式日期
    $stored_date = DateTime::createFromFormat('d/m/Y', $stored_date_str);
    if (!$stored_date) {
        // 格式错误视为需处理
        return true;
    }
    
    // 计算两个月前的日期
    $two_months_ago = new DateTime();
    $two_months_ago->modify('-2 months');
    
    // 比较日期:存储日期早于两个月前则返回true
    return $stored_date < $two_months_ago;
}

3. 动作与过滤器的选择建议

  • wp_login动作:仅在登录成功时触发一次,适合执行首次登录日期写入,不会干扰跳转逻辑,安全性更高。
  • login_redirect过滤器:适合在校验后控制跳转(比如字段为空或日期过期时跳转到指定页面),示例代码:
add_filter('login_redirect', 'check_login_date_on_redirect', 10, 3);
function check_login_date_on_redirect($redirect_to, $requested_redirect_to, $user) {
    if (!is_a($user, 'WP_User')) {
        return $redirect_to;
    }
    
    if (is_login_date_expired($user->ID)) {
        // 跳转到自定义的用户信息更新页面
        return home_url('/update-profile/');
    }
    
    return $redirect_to;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:15:44