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?
1 Answer
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:
function update_last_action_time() {
$user = wp_get_current_user();
update_user_meta($user->ID, 'last_action_time', current_time('mysql'));
}
add_action('admin_init', 'update_last_action_time');
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 deprecated update_usermeta
.
// Edit, again
In case you want to track users on the front-end, put this code in your desired template:
if (is_user_logged_in()) {
$user = wp_get_current_user();
update_user_meta($user->ID, 'last_action_time', current_time('mysql'));
}
Again, to lower the overhead, I’d prefer putting this not into the footer.php
file. I’d rather take home.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 in footer.php
.