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:

View the code on Gist.

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 );

2 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

    Reply
    • 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.

      Reply

Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>