Record and Display WordPress User Last Login Activity

Implement a user activity monitoring system by capturing the exact timestamp of every successful login event. Hook into the wp_login action to save the current time using update_user_meta with a custom last_login key. Retrieve this data using get_user_meta and format it with date_i18n to match your site's time settings. This feature provides valuable security insights for site owners and transparency for users, allowing them to verify recent account access. Easily integrate the display function into member profiles, author boxes, or custom admin tables for better user management.

How to Show WordPress User’s Last Login Timestamp

Advanced Guides Code Snippets Coding Blog PHP PHP Development PHP Snippets Wordpress WordPress Code Snippets WordPress Development WordPress Functions WordPress How-To WordPress Snippets WordPress Theme Development

How to Show WordPress User’s Last Login Timestamp Tutorial/Guide

Want to show when a user last logged in? WordPress doesn’t include this by default, but you can add it using hooks and a simple meta key. Step 1: Edit your active theme’s functions.php file. Step 2: Add this code snippet:

// Capture last login on login event
function update_last_login($user_login) {
    $user = get_user_by('login', $user_login);
    $current_time = current_time('mysql');
    update_user_meta($user->ID, 'last_login', $current_time);
}
add_action('wp_login', 'update_last_login', 10, 2);

// Output last login timestamp
function display_last_login() {
    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        $last_login = get_user_meta($user->ID, 'last_login', true);

        if ($last_login) {
            $formatted = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_login));
            echo 'Last login: ' . $formatted;
        }
    }
}

Step 3: Insert this line into your theme where you want to show the login time:

<?php display_last_login(); ?>

Why Use This?

  • Shows users when they last signed in
  • Enhances security monitoring
  • Helps admins track user activity

Pro Tip: Customize output for user roles, profile pages, or even show in admin tables using admin_init or user_contactmethods filters.  

πŸ’‘ Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.