I’m using the code below to track when a user last logs in. I’m realizing though that if they checked the Remember Me
option, this won’t track their last visit.
// Catch the time they login and save it
function set_last_login($login) {
$user = get_userdatabylogin($login);
update_usermeta( $user->ID, 'last_login', current_time('mysql') );
}
add_action('wp_login', 'set_last_login');
// Function to display the time
function get_last_login($user_id) {
$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;
}
In addition to the working code above for tracking login, I’m looking to see when the user was last active if they are already logged in.
Any tips?
You could create a new entry for the user meta data and update it on every admin pageload.
Put the following in your theme’s
functions.php
or maybe wrap it into a plugin:Of course, you could refine this (and thus lower the overhead) by restricting this to certain pages, for instance, the dashboard only.
// Edit: you should use
update_user_meta
instead of the deprecatedupdate_usermeta
.// Edit, again
In case you want to track users on the front-end, put this code in your desired template:
Again, to lower the overhead, I’d prefer putting this not into the
footer.php
file. I’d rather takehome.php
(if you have one), or check for particular requests (e.g., your home page, meaning:home_url() == 'http://'.$_SERVER['SERVER_NAME']
). But as said before (meaning: below ;)), the overhead is, of course, okay when using it nonetheless infooter.php
.Try the following code which creates a function
display_last_login
that retrieves the current user’s ID, fetches the last login timestamp from the transient storage, and displays it on the screen.}
add_action( ‘wp_login’, ‘set_user_last_login’ );
function set_user_last_login( $user_login ) {
$user = get_user_by( ‘login’, $user_login );
$user_id = $user->ID;
set_transient( ‘user_last_login_’ . $user_id, time() );
}