简体   繁体   中英

How to check when user visited(been active) the site last time

Been looking for a solution for hours and didn't found one I've tried to use the following code

function user_last_login( $user_login, $user ){
update_user_meta( $user->ID, '_last_login', time() );
}
add_action( 'wp_login', 'user_last_login', 10, 2 );

but I figured out that wp_login action hook only triggered when user logs in manually (writing the username and the password and clicking log in) and it's not triggered if he's logged in automaticly ...

Another thing I've tried was this code

add_action('init', 'wpse_session_start', 1);
function wpse_session_start() {
   if(!session_id()) {
      update_user_meta( get_current_user_id(), '_last_login', time() );
      session_start();
    }
}

but this one don't do the work too... Would be very greatfull somebody can offer a way to solve this issue

function user_last_login( $user_login, $user ){
    update_user_meta( $user->ID, '_last_login', time() );
}
add_action( 'wp_login', 'user_last_login', 10, 2 );

For the above function you tried, you have to use following line where you need the last login values.

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

Since you need the time stamp to update every time the user visits a page (not just when they log in), the wp_login hook will obviously not work. Instead, you can hook into init , which runs on every page load:

// Update time stamp
function set_user_last_active() {
    if ( is_user_logged_in() ) {
        update_user_meta( get_current_user_id(), '_last_login', time() );
    }
}
add_action( 'init', 'set_user_last_active' );

You can then get the time stamp using:

get_user_meta( get_current_user_id(), '_last_login', true );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM