WordPress last login foreach user

Trying to get the last login of each user and display it into the admin panel. Currently I can display the first user within the admin loop, however I can’t pull out the remaining users.

I think I need to loop through and pull out each user meta_value where it’s equal to last_login but I’ve tried a standard query and its not working. Code is:

    function modify_user_column( $column_name, $user_id ) {

//get current user object
    $current_user = wp_get_current_user();


    if( 'last_login' != $column_name ) {

            return get_last_login( $current_user->ID );
    }

}
add_action( 'manage_users_custom_column', 'modify_user_column', 10, 2 );

And get_last_login() is:

    function get_last_login($user_id) {

   $last_login = get_user_meta($user_id, 'last_login', false);


  $last_login = get_user_meta($user_id, 'last_login', true);
$date_format = get_option('date_format') . ' ' . get_option('time_format');
$the_last_login = mysql2date($date_format, $last_login, false);
return $the_last_login;

}

Thanks

1 Answer
1

This will add a new column to the Users admin and show their last login.

<?php
/* Plugin Name: (#158276) WPSE | Last user login */

// Add user meta `last_login` that saves the UNIX time stamp 
// to identify the exact time when a user logged in
add_action( 'wp_login', 'add_login_time' );
function add_login_time( $user_login ) {
    global $wpdb;
    $user_id = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_login = %s", $user_login ) );
    update_user_meta( $user_id, 'last_login', current_time('mysql') );
}

// Add a new column to an admin list table
add_filter( 'manage_users_columns', 'add_last_login_column' );
function add_last_login_column( $columns ) {
    $columns['last_login'] = __( 'Last login', 'last_login' );
    return $columns;
}

// Contents of the new admin list table column
add_action( 'manage_users_custom_column',  'add_last_login_column_value', 10, 3 );
function add_last_login_column_value( $value, $column_name, $user_id ) {
    $meta = get_user_meta( $user_id, 'last_login', true );
    if ( 'last_login' == $column_name && $meta ) {
        return date_i18n( 
            sprintf(
                '%s - %s',
                get_option( 'date_format' ),
                get_option( 'time_format' )
            ),
            strtotime( $meta ),
            get_option( 'gmt_offset' )
        );
    }
    return $value;
}

Leave a Comment