Save the date / time of the last log in WordPress

One of the biggest headaches that we find in our projects is to find out who has entered our page and at what time.
If we want to add the functionality to WordPress to save the date / time of the last login we must embed the following code fragment in our functions.php file

 

add_action('wp_login','wpsnipp_set_last_login', 0, 2);
function wpsnipp_set_last_login($login, $user) {
    $user = get_user_by('login',$login);
    $time = current_time( 'timestamp' );
    $last_login = get_user_meta( $user->ID, '_last_login', 'true' );
    if(!$last_login){
    update_usermeta( $user->ID, '_last_login', $time );
    }else{
    update_usermeta( $user->ID, '_last_login_prev', $last_login );
    update_usermeta( $user->ID, '_last_login', $time );
    }
}
// get last login date
function wpsnipp_get_last_login($user_id,$prev=null){
  $last_login = get_user_meta($user_id);
  $time = current_time( 'timestamp' );
  if(isset($last_login['_last_login_prev'][0]) && $prev){
          $last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
  }else if(isset($last_login['_last_login'][0])){
          $last_login = get_user_meta($user_id, '_last_login', 'true' );
  }else{
    update_usermeta( $user_id, '_last_login', $time );
    $last_login = $last_login['_last_login'][0];
  }
  return $last_login;
}

 

Rúa Pilar Miró n 6 Santiago de Compostela

Jersey St , Manchester, Greater Manchester M4 6JG, GB

T. 609 538 171 - 634 59 34 43

info@teslatechnologies.com