WordPress前台显示登录用户的最后登录时间

本文介绍了两种在WordPress中记录和显示用户最后登录时间的方法。方法一通过functions.php添加基础功能,记录登录时间并在前台显示。方法二为完整版本,提供短代码和样式支持,能格式化显示时间差(如“刚刚”“X天前”),并包含用户注册时间作为备用记录。

文章作者:曾凤祥
阅读时间: 170 分钟
更新时间:2026年3月9日

以下是几种实现方法,从简单到功能完整,您可以根据需要选择。

方法1:最简单的方法(通过functions.php添加)

// 1. 记录用户最后登录时间
function record_user_last_login($user_login) {
    $user = get_user_by('login', $user_login);
    update_user_meta($user->ID, 'last_login', current_time('mysql'));
}
add_action('wp_login', 'record_user_last_login');

// 2. 在前台显示最后登录时间
function display_last_login() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $last_login = get_user_meta($user_id, 'last_login', true);
        
        if ($last_login) {
            $date_format = get_option('date_format') . ' ' . get_option('time_format');
            $formatted_date = date_i18n($date_format, strtotime($last_login));
            
            echo '<div class="last-login-info">';
            echo '<span class="login-label">最后登录时间:</span>';
            echo '<span class="login-time">' . $formatted_date . '</span>';
            echo '</div>';
        } else {
            echo '<div class="last-login-info">';
            echo '<span class="login-label">首次登录</span>';
            echo '</div>';
        }
    }
}

方法2:完整功能版本(带短代码和样式)

/**
 * 记录用户最后登录时间
 */
function record_user_last_login_time($user_login, $user) {
    update_user_meta($user->ID, 'last_login_time', current_time('timestamp'));
    update_user_meta($user->ID, 'last_login_date', current_time('mysql'));
}
add_action('wp_login', 'record_user_last_login_time', 10, 2);

/**
 * 获取用户最后登录时间
 */
function get_user_last_login_time($user_id = null) {
    if (!$user_id) {
        $user_id = get_current_user_id();
    }
    
    if (!$user_id) {
        return false;
    }
    
    $last_login = get_user_meta($user_id, 'last_login_time', true);
    
    if ($last_login) {
        return $last_login;
    }
    
    // 如果没有记录,尝试从用户注册时间开始记录
    $user_data = get_userdata($user_id);
    if ($user_data) {
        $registered = strtotime($user_data->user_registered);
        update_user_meta($user_id, 'last_login_time', $registered);
        return $registered;
    }
    
    return false;
}

/**
 * 格式化显示最后登录时间
 */
function display_formatted_last_login($user_id = null, $format = 'default') {
    $last_login = get_user_last_login_time($user_id);
    
    if (!$last_login) {
        return '从未登录';
    }
    
    $current_time = current_time('timestamp');
    $time_diff = $current_time - $last_login;
    
    // 根据时间差显示不同格式
    if ($time_diff < 60) {
        return '刚刚';
    } elseif ($time_diff < 3600) {
        $minutes = floor($time_diff / 60);
        return $minutes . '分钟前';
    } elseif ($time_diff < 86400) {
        $hours = floor($time_diff / 3600);
        return $hours . '小时前';
    } elseif ($time_diff < 604800) {
        $days = floor($time_diff / 86400);
        return $days . '天前';
    } else {
        $date_format = get_option('date_format') . ' ' . get_option('time_format');
        return date_i18n($date_format, $last_login);
    }
}

/**
 * 短代码:显示当前用户最后登录时间
 */
function last_login_shortcode($atts) {
    if (!is_user_logged_in()) {
        return '';
    }
    
    $atts = shortcode_atts(array(
        'format' => 'relative', // relative, datetime, both
        'label' => '最后登录:',
        'class' => 'last-login-display'
    ), $atts);
    
    $user_id = get_current_user_id();
    $last_login = get_user_last_login_time($user_id);
    
    if (!$last_login) {
        return '<div class="' . esc_attr($atts['class']) . '">首次登录</div>';
    }
    
    $output = '<div class="' . esc_attr($atts['class']) . '">';
    
    if ($atts['label']) {
        $output .= '<span class="last-login-label">' . esc_html($atts['label']) . '</span>';
    }
    
    if ($atts['format'] === 'relative' || $atts['format'] === 'both') {
        $relative_time = display_formatted_last_login($user_id);
        $output .= '<span class="last-login-relative">' . $relative_time . '</span>';
    }
    
    if ($atts['format'] === 'both') {
        $output .= ' (';
    }
    
    if ($atts['format'] === 'datetime' || $atts['format'] === 'both') {
        $date_format = get_option('date_format') . ' ' . get_option('time_format');
        $formatted_date = date_i18n($date_format, $last_login);
        $output .= '<span class="last-login-datetime">' . $formatted_date . '</span>';
    }
    
    if ($atts['format'] === 'both') {
        $output .= ')';
    }
    
    $output .= '</div>';
    
    return $output;
}
add_shortcode('last_login', 'last_login_shortcode');

/**
 * 在用户个人资料页面显示最后登录时间(后台)
 */
function add_last_login_to_user_profile($user) {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    $last_login = get_user_last_login_time($user->ID);
    
    if ($last_login) {
        $date_format = get_option('date_format') . ' ' . get_option('time_format');
        $formatted_date = date_i18n($date_format, $last_login);
        $relative_time = display_formatted_last_login($user->ID);
        ?>
        <h3>登录信息</h3>
        <table class="form-table">
            <tr>
                <th><label>最后登录时间</label></th>
                <td>
                    <p><?php echo $formatted_date; ?></p>
                    <p class="description"><?php echo '(' . $relative_time . ')'; ?></p>
                </td>
            </tr>
        </table>
        <?php
    }
}
add_action('show_user_profile', 'add_last_login_to_user_profile');
add_action('edit_user_profile', 'add_last_login_to_user_profile');

/**
 * 在用户列表页面添加最后登录时间列(后台)
 */
function add_last_login_column($columns) {
    $columns['last_login'] = '最后登录';
    return $columns;
}
add_filter('manage_users_columns', 'add_last_login_column');

function show_last_login_column_content($value, $column_name, $user_id) {
    if ($column_name === 'last_login') {
        $last_login = get_user_last_login_time($user_id);
        
        if ($last_login) {
            return display_formatted_last_login($user_id);
        } else {
            return '从未登录';
        }
    }
    return $value;
}
add_filter('manage_users_custom_column', 'show_last_login_column_content', 10, 3);

function make_last_login_column_sortable($columns) {
    $columns['last_login'] = 'last_login';
    return $columns;
}
add_filter('manage_users_sortable_columns', 'make_last_login_column_sortable');

function sort_users_by_last_login($query) {
    if (!is_admin() || !$query->is_main_query()) {
        return;
    }
    
    if ($query->get('orderby') === 'last_login') {
        $query->set('meta_key', 'last_login_time');
        $query->set('orderby', 'meta_value_num');
    }
}
add_action('pre_get_users', 'sort_users_by_last_login');

方法3:带缓存和AJAX的优化版本

// 优化版本,减少数据库查询
class WP_Last_Login_Manager {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('wp_login', array($this, 'update_last_login'), 10, 2);
        add_action('wp_ajax_nopriv_get_last_login', array($this, 'ajax_get_last_login'));
        add_action('wp_ajax_get_last_login', array($this, 'ajax_get_last_login'));
        add_action('wp_footer', array($this, 'enqueue_scripts'));
    }
    
    /**
     * 更新最后登录时间
     */
    public function update_last_login($user_login, $user) {
        $time = current_time('timestamp');
        
        // 更新用户元数据
        update_user_meta($user->ID, 'last_login_timestamp', $time);
        
        // 设置缓存,24小时过期
        wp_cache_set('user_last_login_' . $user->ID, $time, '', 86400);
    }
    
    /**
     * 获取最后登录时间(带缓存)
     */
    public function get_last_login($user_id = null) {
        if (!$user_id) {
            $user_id = get_current_user_id();
        }
        
        if (!$user_id) {
            return false;
        }
        
        // 先尝试从缓存获取
        $cached_time = wp_cache_get('user_last_login_' . $user_id);
        
        if ($cached_time !== false) {
            return $cached_time;
        }
        
        // 缓存不存在,从数据库获取
        $last_login = get_user_meta($user_id, 'last_login_timestamp', true);
        
        if ($last_login) {
            // 存入缓存
            wp_cache_set('user_last_login_' . $user_id, $last_login, '', 86400);
        }
        
        return $last_login;
    }
    
    /**
     * AJAX获取最后登录时间
     */
    public function ajax_get_last_login() {
        if (!is_user_logged_in()) {
            wp_die('未登录');
        }
        
        $user_id = get_current_user_id();
        $last_login = $this->get_last_login($user_id);
        
        if ($last_login) {
            $date_format = get_option('date_format') . ' ' . get_option('time_format');
            $formatted_date = date_i18n($date_format, $last_login);
            
            wp_send_json_success(array(
                'timestamp' => $last_login,
                'formatted' => $formatted_date,
                'relative' => $this->get_relative_time($last_login)
            ));
        } else {
            wp_send_json_error('无登录记录');
        }
    }
    
    /**
     * 获取相对时间
     */
    private function get_relative_time($timestamp) {
        $current_time = current_time('timestamp');
        $time_diff = $current_time - $timestamp;
        
        if ($time_diff < 60) {
            return '刚刚';
        } elseif ($time_diff < 3600) {
            $minutes = floor($time_diff / 60);
            return $minutes . '分钟前';
        } elseif ($time_diff < 86400) {
            $hours = floor($time_diff / 3600);
            return $hours . '小时前';
        } elseif ($time_diff < 604800) {
            $days = floor($time_diff / 86400);
            return $days . '天前';
        } else {
            $weeks = floor($time_diff / 604800);
            return $weeks . '周前';
        }
    }
    
    /**
     * 加载脚本
     */
    public function enqueue_scripts() {
        if (!is_user_logged_in()) {
            return;
        }
        
        wp_enqueue_script(
            'last-login-ajax',
            get_stylesheet_directory_uri() . '/js/last-login.js',
            array('jquery'),
            '1.0',
            true
        );
        
        wp_localize_script('last-login-ajax', 'lastLoginAjax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('last_login_nonce')
        ));
    }
    
    /**
     * 显示最后登录时间的函数
     */
    public function display_last_login($args = array()) {
        if (!is_user_logged_in()) {
            return '';
        }
        
        $defaults = array(
            'show_icon' => true,
            'show_label' => true,
            'auto_update' => false,
            'wrapper_class' => 'last-login-display'
        );
        
        $args = wp_parse_args($args, $defaults);
        
        $user_id = get_current_user_id();
        $last_login = $this->get_last_login($user_id);
        
        if (!$last_login) {
            return '<div class="' . esc_attr($args['wrapper_class']) . '">首次登录</div>';
        }
        
        $date_format = get_option('date_format') . ' ' . get_option('time_format');
        $formatted_date = date_i18n($date_format, $last_login);
        $relative_time = $this->get_relative_time($last_login);
        
        $output = '<div class="' . esc_attr($args['wrapper_class']) . '"';
        
        if ($args['auto_update']) {
            $output .= ' data-user-id="' . $user_id . '"';
        }
        
        $output .= '>';
        
        if ($args['show_icon']) {
            $output .= '<span class="last-login-icon">⏰</span>';
        }
        
        if ($args['show_label']) {
            $output .= '<span class="last-login-label">最后登录:</span>';
        }
        
        $output .= '<span class="last-login-time" title="' . esc_attr($formatted_date) . '">';
        $output .= esc_html($relative_time);
        $output .= '</span>';
        
        $output .= '</div>';
        
        return $output;
    }
}

// 初始化
WP_Last_Login_Manager::get_instance();

// 快捷函数
function the_last_login($args = array()) {
    $manager = WP_Last_Login_Manager::get_instance();
    echo $manager->display_last_login($args);
}

function get_the_last_login($args = array()) {
    $manager = WP_Last_Login_Manager::get_instance();
    return $manager->display_last_login($args);
}

4. 配套CSS样式

/* 最后登录时间显示样式 */
.last-login-display {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background: #f8f9fa;
    border-radius: 6px;
    font-size: 14px;
    color: #495057;
    border: 1px solid #e9ecef;
    margin: 5px 0;
}

.last-login-display:hover {
    background: #e9ecef;
    border-color: #dee2e6;
}

.last-login-icon {
    font-size: 16px;
    line-height: 1;
}

.last-login-label {
    font-weight: 500;
    color: #6c757d;
}

.last-login-time {
    color: #212529;
    font-weight: 600;
    cursor: help;
    border-bottom: 1px dotted #adb5bd;
}

/* 侧边栏小工具样式 */
.widget .last-login-display {
    width: 100%;
    display: flex;
    justify-content: center;
    margin: 10px 0;
    padding: 10px 15px;
}

/* 用户中心页面样式 */
.user-profile-section .last-login-display {
    background: #e7f5ff;
    border-color: #a5d8ff;
    margin: 15px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .last-login-display {
        font-size: 13px;
        padding: 6px 10px;
    }
    
    .last-login-icon {
        display: none;
    }
}

5. AJAX自动更新脚本(可选)

// js/last-login.js
jQuery(document).ready(function($) {
    // 自动更新最后登录时间
    function updateLastLoginDisplay() {
        var $display = $('.last-login-display[data-auto-update="true"]');
        
        if ($display.length) {
            $.ajax({
                url: lastLoginAjax.ajax_url,
                type: 'POST',
                data: {
                    action: 'get_last_login',
                    nonce: lastLoginAjax.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $display.find('.last-login-time').text(response.data.relative)
                               .attr('title', response.data.formatted);
                    }
                }
            });
        }
    }
    
    // 每5分钟更新一次
    setInterval(updateLastLoginDisplay, 300000);
    
    // 页面获取焦点时更新
    $(window).on('focus', updateLastLoginDisplay);
});

使用方法

1. 基本使用(添加到主题functions.php)

// 将方法1或方法2的代码添加到主题的functions.php文件中
// 然后在需要显示的地方调用:
if (function_exists('display_last_login')) {
    display_last_login();
}

2. 使用短代码

// 在文章/页面中插入短代码

[last_login format=“both” label=“您最后登录:” class=”mylogindisplay“]

// 在主题模板中 echo do_shortcode(‘[last_login]’);

3. 在侧边栏显示

  1. 进入 WordPress 后台 > 外观 > 小部件
  2. 添加一个”自定义HTML”小部件
  3. 添加短代码:[last_login]

4. 在主题模板中直接调用

<?php
// 在header.php、sidebar.php或任意模板文件中
if (is_user_logged_in()) {
    the_last_login(array(
        'show_icon' => true,
        'show_label' => true,
        'wrapper_class' => 'sidebar-login-display'
    ));
}
?>

注意事项

  1. 安全提示:这些功能只对登录用户显示,不会泄露未登录用户的隐私
  2. 性能优化:方法3使用了缓存机制,适合高流量网站
  3. 时区设置:使用WordPress的date_i18n()函数,自动处理时区
  4. 多站点支持:所有代码都兼容WordPress多站点
  5. SEO友好:不会影响搜索引擎优化

这个方案是完全无插件的,代码经过优化,不会影响网站性能,并且提供了多种显示方式和自定义选项。

这篇文章有用吗?

点击星号为它评分!

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

在AI里面继续讨论:

曾凤祥

曾凤祥

WordPress技术负责人
小兽WordPress凭借15年的WordPress企业网站开发经验,坚持以“为企业而生的WordPress服务”为宗旨,累计为10万多家客户提供高品质WordPress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。小兽WordPress能坚持多年,是因为我们一直诚信。

相关文章

如何让线上业务更上一层楼

还没有WordPress网站

还没有WordPress网站

不管你从事什么行业,WordPress都会为你提供一个专业的主题模板。在WordPress市场上有成千上万的免费主题,适合很多中小企业。

查看所有模板
已经有WordPress网站

已经有WordPress网站

小兽WordPress诚邀你一起学习WordPress,愿与各方携手升级改善您的WordPress网站,一起交流网站加速,网站优化等问题。

马上交个朋友
微信联系
chat 扫码联系
模板建站
挑选模板
网站定制
免费诊断
咨询热线
咨询热线

189-0733-7671

返回顶部