1

I've created my own code based on this good article - https://shocksolution.com/2019/04/16/find-last-login-time-for-wordpress-users-in-the-sql-database/ to get the last login date for a user.

I'm finding that not all users have a 'session_tokens' meta_key record in the usermata table despite having logged in several times.

Could some one explain that please?

Many thanks

0

1 Answer 1

1

When a session is destroyed, it's removed from the list in the meta. Importantly, if the list is empty, the meta is deleted.

So if a user logs out, if a session expires, if a user is deleted, or if the user clears their sessions on their profile page, these can all result in no sessions, so no user meta.

The root problem is a misunderstanding of what these sessions are. It is not the time of the last login, it is the time that the active sessions started. If there are no active sessions there are no sessions to list.

So, if I log in on a desktop on Monday, a mobile on Tuesday, and then log out of the mobile on Wednesday, your code will say I last logged in Monday, not Tuesday. The session for the mobile ended, and was cleaned up.

This way, it is possible to log in without detection. This method cannot be used to reliably detect the last time the user was seen.

WordPress has no built in way to determine when the last time a user logged in. To do this you need to write code to track this or add a plugin that does this.

5
  • Great explanation - Thank you very much. Sep 16, 2020 at 15:08
  • thanks, if it answers your question could you mark it as the accepted answer?
    – Tom J Nowell
    Sep 26, 2020 at 23:45
  • I had the same question so thanks a lot for your explication. What is your advice if I wont to know the last login ? Is ther a snippet to do that ?
    – Fred17
    Feb 3, 2023 at 14:51
  • @Fred17 don't post comments as answers, I've converted it into a comment using moderation powers, but do not do it again! It put a flag on your answer which could get you auto-banned or moderated by the site in the future if it happens again.
    – Tom J Nowell
    Feb 3, 2023 at 16:36
  • @Fred17 also, if you want that you should ask a new question, but if you are not recording that information then that information does not exist. If you want to know when a user last logged in you have to record and store that somewhere. WordPress does not do this for you. As for a code snippet to do this, you should ask your own new question, not a comment, your question is related but not the same!
    – Tom J Nowell
    Feb 3, 2023 at 16:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.