Showing the Last Login Date for a User in a WordPress Website
In today’s world, giving a personalized experience to the users helps the website to garner popularity and be successful in the online world. Now, there are many little things that help you give a personalized experience to users. One such little thing is showing the last login date for a particular user. In this post we would be looking at the technique with which you can do that.
The Technique
To show the last login time of a user anywhere on your site, you just need to add the following code in the functions.php file of your theme
01 |
<?php |
02 |
/** |
03 |
* Capture user login and add it as timestamp in user meta data |
04 |
* |
05 |
*/ |
06 |
|
07 |
function user_last_login( $user_login, $user ) { |
08 |
update_user_meta( $user->ID, 'last_login', time() ); |
09 |
} |
10 |
add_action( 'wp_login', 'user_last_login', 10, 2 ); |
11 |
|
12 |
/** |
13 |
* Display last login time |
14 |
* |
15 |
*/ |
16 |
|
17 |
function wpb_lastlogin() { |
18 |
$last_login = get_the_author_meta('last_login'); |
19 |
$the_login_date = human_time_diff($last_login); |
20 |
return $the_login_date; |
21 |
} |
22 |
|
23 |
/** |
24 |
* Add Shortcode lastlogin |
25 |
* |
26 |
*/ |
27 |
|
28 |
add_shortcode('lastlogin','wpb_lastlogin'); |
29 |
?> |
With this code, you would add the last login time as a meta key. Whenever a user logs in, the time would be saved as a meta key value. You can then display this meta key value using [lastlogin] shortcode in your WordPress posts and widgets.
By using the above code, the time would be shown as a relative value to the present, like ‘an hour ago’. If you wish to show the exact date, then just find the below given line in the code
19 |
$the_login_date = human_time_diff($last_login); |
And replace it with this line
19 $the_login_date = date('M j, Y h:i a', $last_login);
If you are based out of Houston, then you can take the help from the leading names in Website Design Houston as they would help you make such little but useful changes to your website.
They are widely regarded as the experts in WordPress website design and they would know just how to create the perfect WordPress site for your business. The most well-known names in Website Design in Houston would help you design a site that your visitors would find to be useful. So, get in touch with the experts and make your website truly user-centric.