riseagainst
riseagainst

Reputation: 430

Display user's last visit on wordpress

I'm trying to display the user's last visit, not the last login. I've come across this code, which I've come to realize now, works exactly as intended, to show the last login, which is not what I want to display, since for example, I'm myself have been logged for over a week, when this is displayed, it gives the impression that I haven't been on the site for over a week (Last Seen:), which is incorrect. I'm trying to display the last time a user was seen on the site. Any ideas?

http://www.wpbeginner.com/plugins/how-to-show-users-last-login-date-in-wordpress/

<?php 
/**
 * Capture user login and add it as timestamp in user meta data
 *
 */
 
function user_last_login( $user_login, $user ) {
    update_user_meta( $user->ID, 'last_login', time() );
}
add_action( 'wp_login', 'user_last_login', 10, 2 );
 
 
function wpb_lastlogin() { 
    $last_login = get_the_author_meta('last_login');
    $the_login_date = human_time_diff($last_login);
    return $the_login_date; 
} 
  
add_shortcode('lastlogin','wpb_lastlogin');
?>

<?php echo 'Last seen: '. do_shortcode('[lastlogin]') .' ago'; ?>

Upvotes: 3

Views: 2243

Answers (1)

You are running your code on a hook "wp_login" which of course will run only when you login instead of running each time you refresh a page. The fallowing code should work each time a logged in user refreshes the site:

<?php 
/**
 * Capture timestamp of active user
 *
 */

function user_last_seen() {
    if ( is_user_logged_in() ) {
        update_user_meta( get_current_user_id(), 'last_seen', time() );
    } else {
        return;
    }

}
add_action( 'wp_footer', 'user_last_seen', 10 );


function wp_lastseen() { 
    $last_seen = get_the_author_meta('last_seen');
    $the_last_seen_date = human_time_diff($last_seen);
    return $the_last_seen_date; 
} 

add_shortcode('lastseen','wp_lastseen');
?>

<?php echo 'Last seen: '. do_shortcode('[lastseen]') .' ago'; ?>

This script will update the lastseen shortcode date each time the user refreshes a page in your site.

Upvotes: 2

Related Questions