WordPress User Last Login

Have you ever needed to know a WordPress user last login date?  By default, WordPress doesn’t provide any information on when a user last logged in.  However, such information is extremely useful when, for example, trying to delete inactive users or evaluate the success of a membership site.

The User Meta API

Thankfully, WordPress allows you to store additional information on users.  This additional information is known as user meta and, as of WordPress 3.0, can be managed using a few basic functions:

Saving the WordPress User Last Login

Let’s take a quick look at the code that will actually save the timestamp of a user’s last login:

We use the wp_login action to get the user object when a user logs on.  All we do then is use the time() function to fetch the current timestamp and save it as user meta.  To fetch the last login for a user later, this is all we have to do:

get_user_meta( $user->ID, '_last_login', true );

Comments

  1. H there, Where do I put the number of the user ID?
    I’m for example is user “2” but how do I implement this in the code so that it only get and displays latest login from user 2?
    Thank you

    1. The code example will record the timestamp for the last login for all users, which is probably the ideal scenario. However, if you only want to track a single user, you could add an if(2 == $user-ID) conditional around the update_user_meta() function call.

  2. Will this add a new record to the usermeta table everytime the same user logs in or will it just update the existent record?

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.