Track and Display Last Login Time in WordPress

Code Snippets Custom Code Snippets PHP PHP Development Plugins Theme Optimization Woocommerce Wordpress WordPress Development WordPress Hacks WordPress Tips WP Best Practices

Track and Display Last Login Time in WordPress Tutorial/Guide

You can display a user's last login time in WordPress by hooking into the login process and saving the login timestamp. Here's how to set this up: Step 1: Open your theme’s functions.php file. Step 2: Add the following code snippet:

// Record last login time
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);

// Display last login time
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 = date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($last_login));
            echo 'Last login: ' . $formatted_date;
        }
    }
}

Step 3: Save the file and upload it. Step 4: Use this line where you want the login time displayed:

<?php display_last_login(); ?>
  1. Why Display Last Login Time?
    • Boosts user transparency
    • Improves trust and accountability
    • Enhances login security awareness
  2. Technical Breakdown
    • Hooks: wp_login
    • Functions: get_user_by(), update_user_meta()
    • Formatting: date_i18n()
  3. Customization Ideas
    • Show login time only to admins
    • Display user info along with login
    • Enhance output via styling or shortcodes
  4. SEO & Privacy Tips
    • Use clean meta keys (e.g., last_login)
    • Respect user roles and privacy settings
    • Avoid showing sensitive data to others

 

💡 Have a Coding Problem?

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