WordPress中显示用户最后访问时间而非登录时间的技术问询
如何在WordPress中显示用户最后活跃时间(替代最后登录时间)
兄弟,我完全懂你的困扰——连续登录好几天,结果显示的“最后访问”还是上次登录的时间,这用户看了肯定懵。别慌,我给你一套靠谱的方案,从记录用户真正的活跃时间到前端显示,一步搞定:
第一步:让WordPress记录用户的活跃时间
WordPress默认只存“最后登录时间”,咱们得自己加个字段来记录用户每次浏览页面、登录这些活跃行为的时间。把下面的代码放到你的主题functions.php里,或者更稳妥的自定义插件中:
// 每次用户浏览前台页面时,更新最后活跃时间(15分钟内不重复更新,减少数据库压力) function update_user_last_active() { if (is_user_logged_in() && !is_admin()) { $current_user = wp_get_current_user(); $last_active = get_user_meta($current_user->ID, 'last_active', true); // 15分钟=900秒,可根据需求调整这个时间间隔 if (empty($last_active) || (time() - $last_active) > 900) { update_user_meta($current_user->ID, 'last_active', time()); } } } add_action('template_redirect', 'update_user_last_active'); // 用户登录时,也同步更新最后活跃时间 function update_last_active_on_login($user_login, $user) { update_user_meta($user->ID, 'last_active', time()); } add_action('wp_login', 'update_last_active_on_login', 10, 2);
第二步:写个函数来获取并格式化活跃时间
接下来咱们需要一个函数,用来读取刚才记录的时间,要是没记录的话就 fallback 到用户的最后登录时间(或者注册时间,看你需求):
function get_user_last_active($user_id) { $last_active = get_user_meta($user_id, 'last_active', true); // 如果没有活跃记录,就用最后登录时间(WordPress 4.0+支持last_login字段) if (empty($last_active)) { $user = get_userdata($user_id); $last_active = !empty($user->last_login) ? strtotime($user->last_login) : strtotime($user->user_registered); } // 用WordPress默认的日期时间格式来显示,也可以自定义格式 return date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $last_active); }
第三步:在前端显示最后活跃时间
现在就可以在你需要的地方调用这个函数了,比如:
- 在作者档案页(author.php)显示作者的最后活跃时间:
$author_id = get_queried_object_id(); echo '<p>作者最后活跃:' . get_user_last_active($author_id) . '</p>';
- 在评论区显示评论者的最后活跃时间(放到评论循环里):
$comment_author_id = get_comment_author_meta('ID'); if ($comment_author_id) { echo '<span class="comment-last-active">评论者最后活跃:' . get_user_last_active($comment_author_id) . '</span>'; }
- 在用户个人资料页显示:
比如在主题的user-profile.php或者用短代码(可以自己写个短代码函数):
// 注册短代码,方便在编辑器里调用 function last_active_shortcode($atts) { $atts = shortcode_atts(array('user_id' => get_current_user_id()), $atts); return get_user_last_active($atts['user_id']); } add_shortcode('last_active', 'last_active_shortcode');
然后在编辑器里用[last_active]显示当前用户的最后活跃时间,或者[last_active user_id="123"]显示指定用户的。
一些小提示
- 要是想记录用户在后台的操作活跃,把第一个函数里的
!is_admin()去掉就行。 - 时间间隔(900秒)可以自己调整,比如改成300秒(5分钟),更精准但会增加一点数据库操作。
- 推荐用自定义插件来放这些代码,避免主题更新后代码丢失。
内容的提问来源于stack exchange,提问作者riseagainst
相关产品推荐
相关产品推荐

