WordPress latest user login hack

I needed a way to log the date and time the last time a user logged in I looked around for a plugin to do this for me, but found none, so I decided to try and write a function myself.

This one I struggled with and in the end it came out like something of a abomination of a function, but at least it gets the job done. It uses the WP_AUTHENTICATE hook to call the function where a simple login check is done, and if successful, the timestamp is writted to the wp_users table.

You can either insert a new field called user_lastlogin (or what you prefer) in wp_users like I did, or you can make a new table to store the login log.

The code follows below. Happy logging!


function update_last_login($user_login='', $user_pass='', $cookie=false)
{
if ($_POST) {
global $wpdb;
$success=0;
// check login $_POST variables against database
$query = "SELECT ID FROM wp_users WHERE user_login='$user_login[0]' AND user_pass='".md5($user_login[1])."'";
$uid = $wpdb->get_var($query);
if ($uid!='') {$success=1;}
$login_time = date("Y-m-d H:i:s", time()+28800);
// if login is successful, update user last login
if ($success==1) {
$query = "UPDATE wp_users SET user_lastlogin='$login_time' WHERE user_login='$user_login[0]'";
$wpdb->query($query);
}
}
}
// Hook action -- this is needed to call the function when someone logs in
add_action('wp_authenticate','bm_update_last_login',10,2);

Popularity: 6% [?]

One Response to WordPress latest user login hack

  1. arwannidis1973 | #1

    Google Company Address