Categories
WordPress

How To Store The Last Visit of Users

If you need to monitor when a user last accessed the site, maybe to gather stats of active and not active registered users, you can do it very easily in few lines of code.

add_action('template_redirect', function() {
  if (is_user_logged_in()) {
    update_user_meta(get_current_user_id(), 'last_visit', time());
  }
});

Of course you can attach your code to other hook, like the init hook. Attaching to template_redirect could avoid storing the last visit due to ajax call or other kind of requests.

That could be a wanted or unwanted behavior, it is up to you. To attach to the init event:

add_action('init', function() {
  if (is_user_logged_in()) {
    update_user_meta(get_current_user_id(), 'last_visit', time());
  }
});

The init event is fired to let all plugins to initialize after they have been loaded. If you need to track the user visit after all plugins have been initialized because you need one of them in your visit tracking function, you can alternatively add a low priority to your action (remember low corresponds to in high priority number!).

add_action('init', function() {
  if (is_user_logged_in()) {
    update_user_meta(get_current_user_id(), 'last_visit', time());
  }
}, 1000);

Or you can attach to the wp_loaded event which is the last one in the WP initialization process.

add_action('wp_loaded', function() {
  if (is_user_logged_in()) {
    update_user_meta(get_current_user_id(), 'last_visit', time());
  }
});

Note: all that reasoning is ok only if your installed plugins are well written!

Leave a Reply