How to check if a user (not current user) is logged in?

I need to display the online status (online/offline) for each author page (custom author page template).

is_user_logged_in() only applies to the current user and I can’t find a relevant approach targeting the current author e.g. is_author_logged_in()

Read More

Any ideas?

Answer

One Trick Pony was kind enough to prepare the coding for two to three functions using transients, something I hadn’t use before.

http://codex.wordpress.org/Transients_API

Add this to functions.php:

add_action('wp', 'update_online_users_status');
function update_online_users_status(){

  if(is_user_logged_in()){

    // get the online users list
    if(($logged_in_users = get_transient('users_online')) === false) $logged_in_users = array();

    $current_user = wp_get_current_user();
    $current_user = $current_user->ID;  
    $current_time = current_time('timestamp');

    if(!isset($logged_in_users[$current_user]) || ($logged_in_users[$current_user] < ($current_time - (15 * 60)))){
      $logged_in_users[$current_user] = $current_time;
      set_transient('users_online', $logged_in_users, 30 * 60);
    }

  }
}

Add this to author.php (or another page template):

function is_user_online($user_id) {

  // get the online users list
  $logged_in_users = get_transient('users_online');

  // online, if (s)he is in the list and last activity was less than 15 minutes ago
  return isset($logged_in_users[$user_id]) && ($logged_in_users[$user_id] > (current_time('timestamp') - (15 * 60)));
}

$passthis_id = $curauth->ID;
if(is_user_online($passthis_id)){
echo 'User is online.';}
else {
echo'User is not online.';}

Second Answer (do not use)

This answer is included for reference. As pointed out by One Trick Pony, this is undesireable approach because the database is updated on each page load. After further scrutiny the code only seemed to be detecting the current user’s log-in status rather than additionally matching it to the current author.

1) Install this plugin: http://wordpress.org/extend/plugins/who-is-online/

2) Add the following to your page template:

//Set the $curauth variable
if(isset($_GET['author_name'])) :
$curauth = get_userdatabylogin($author_name);
else :
$curauth = get_userdata(intval($author));
endif;

// Define the ID of whatever authors page is being viewed.
$authortemplate_id = $curauth->ID;

// Connect to database.
global $wpdb;
// Define table as variable.
$who_is_online_table = $wpdb->prefix . 'who_is_online';
// Query: Count the number of user_id's (plugin) that match the author id (author template page).
$onlinestatus_check = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM ".$who_is_online_table." WHERE user_id = '".$authortemplate_id."';" ) );

// If a match is found...
if ($onlinestatus_check == "1"){
echo "<p>User is <strong>online</strong> now!</p>";
}
else{
echo "<p>User is currently <strong>offline</strong>.</p>";
}

Related posts

Leave a Reply

3 comments

  1. I would use transients to do this:

    • create a user-online-update function that you hook on init; it would look something like this:

      // get the user activity the list
      $logged_in_users = get_transient('online_status');
      
      // get current user ID
      $user = wp_get_current_user();
      
      // check if the current user needs to update his online status;
      // he does if he doesn't exist in the list
      $no_need_to_update = isset($logged_in_users[$user->ID])
      
          // and if his "last activity" was less than let's say ...15 minutes ago          
          && $logged_in_users[$user->ID] >  (time() - (15 * 60));
      
      // update the list if needed
      if(!$no_need_to_update){
        $logged_in_users[$user->ID] = time();
        set_transient('online_status', $logged_in_users, $expire_in = (30*60)); // 30 mins 
      }
      

      So this should run on each page load, but the transient will be updated only if required. If you have a large number of users online you might want to increase the “last activity” time frame to reduce db writes, but 15 minutes is more than enough for most sites…

    • now to check if the user is online, simply look inside that transient to see if a certain user is online, just like you did above:

      // get the user activity the list
      $logged_in_users = get_transient('online_status');
      
      // for eg. on author page
      $user_to_check = get_query_var('author'); 
      
      $online = isset($logged_in_users[$user_to_check])
         && ($logged_in_users[$user_to_check] >  (time() - (15 * 60)));
      

    The transient expires in 30 minutes if there’s no activity at all. But in case you have users online all the time it won’t expire, so you might want to clean-up that transient periodically by hooking another function on a twice-daily event or something like that. This function would remove old $logged_in_users entries…

  2. To my knowledge there is not a way to do this using the built-in WordPress functions, but don’t let that discourage you; write a plugin!

    One way you could do this is by creating a new table in the database that simply tracks the last time the user was active on the site. You could also have a settings page for your plugin that determined how long you would consider a registered user to be “Logged in”.

    You would implement this using a WordPress hook. I’d start by hooking into the login, so that once a user logs in, your plugin logs the time in the database. You could then explore other things like setting their status to ‘away’ if they click logout, or ‘idle’ if their login time was more than two hours ago.

    You would run into an issue if they are logged in and active on the site, but past this two hour window. In this case, you’d need to be hooked into the wp-admin section so that anytime they do anything in wp-admin it updates your database to the current time.

    Then, on the posts, you would need to do two things: get the author of the current post:

    <?php $user_login = the_author_meta( $user_login ); ?>
    

    then query your database to determine if they are logged in:

    <?php if your_plugin_function($user_login)... ?>
    ...display something...
    
  3. I decided to revisit the given answer and adjust it to the fit the comments.

    One thing that was talked about in the comment was some kind of daily transient cleaner. As pointed out by @onetrickpony we can use wp_schedule_event() to setup a daily reset.

    I decided to implement an easy way to fetch all users currently online and recently offline.

    The whole thing is object oriented based, packaged into a class.

    Table of contents
    Get a specific user activity status from it’s ID.
    Get an array of all users currently online.
    Get an array of all users recently offline.
    Schedules a recurring daily event to delete the user activity transient.
    Packaging it all in a nice plugin.

    if ( ! class_exists( 'WPC_User_Activity_Monitoring' ) ) {
    
        class WPC_User_Activity_Monitoring {
    
            /**
             * @var Integer User inactivity margin in minutes.
             */
            private const USER_INACTIVITY_MARGIN = 10 * MINUTE_IN_SECONDS;
    
            /**
             * @var Integer Transient self clear margin in minutes.
             */
            private const TRANSIENT_SELF_CLEAR = 30 * MINUTE_IN_SECONDS;
    
            /**
             * Hooks methods on to a sets of actions.
             *
             * @since 1.0.0
             */
            public function __construct() {
    
                add_action( 'init', array( $this, 'wpc_user_activity_monitoring_transient' ) );
    
            }
            
            /**
             * Set & update WPC user activity monitoring transient on user server interactions.
             *
             * @since 1.0.0
             *
             * @param Integer $user_id The user ID.
             *
             * @return Bool True for online.
             */
            public function wpc_user_activity_monitoring_transient() {
            
                if ( is_user_logged_in() ) {
    
                    $wpc_user_activity_monitoring_transient = get_transient( 'wpc_user_activity_monitoring_transient' );
            
                    if ( empty( $wpc_user_activity_monitoring_transient ) ) {
        
                        $wpc_user_activity_monitoring_transient = array();
        
                    };
                
                    $user_id = get_current_user_id();
                    
                    $timestamp = current_time( 'timestamp' );
        
                    if ( empty( $wpc_user_activity_monitoring_transient[$user_id] ) || ( $wpc_user_activity_monitoring_transient[$user_id] < ( $timestamp - self::USER_INACTIVITY_MARGIN ) ) ) {
        
                        $wpc_user_activity_monitoring_transient[$user_id] = $timestamp;
        
                        set_transient( 'wpc_user_activity_monitoring_transient', $wpc_user_activity_monitoring_transient, self::TRANSIENT_SELF_CLEAR );
        
                    };
            
                };
            
            }
            
            /**
             * Get a specific user activity status from it's ID.
             *
             * @since 1.0.0
             *
             * @param Integer $user_id The user ID.
             *
             * @return Bool True for online.
             */
            public function is_user_currently_online( $user_id ) {
            
                $wpc_user_activity_monitoring_transient = get_transient( 'wpc_user_activity_monitoring_transient' );
    
                if ( ! isset( $wpc_user_activity_monitoring_transient[$user_id] ) ) {
                    return;
                };
    
                if ( $wpc_user_activity_monitoring_transient[$user_id] > ( current_time( 'timestamp' ) - self::USER_INACTIVITY_MARGIN ) ) {
        
                    return isset( $wpc_user_activity_monitoring_transient[$user_id] );
        
                };
    
            }
            
            /**
             * Get an array of all users currently online.
             *
             * @since 1.0.0
             *
             * @param Integer $nusers Number of currently online users to retrieve.
             *
             * @return Array An array of currently online users ID.
             */
            public function get_currently_online_nusers() {
            
                $wpc_user_activity_monitoring_transient = array_reverse( get_transient( 'wpc_user_activity_monitoring_transient' ), true );
                
                $currently_online_nusers = array();
        
                foreach ( $wpc_user_activity_monitoring_transient as $user_id => $timestamp ) {
        
                    if ( $timestamp > ( current_time( 'timestamp' ) - self::USER_INACTIVITY_MARGIN ) ) {
        
                        array_push( $currently_online_nusers, $user_id );
        
                    };
        
                };
        
                return $currently_online_nusers;
            
            }
    
            /**
             * Get an array of all users recently offline.
             *
             * @since 1.0.0
             *
             * @param Integer $nusers Number of recently offline users to retrieve.
             *
             * @return Array An array of recently offline users ID.
             */
            public function get_recently_offline_nusers() {
            
                $wpc_user_activity_monitoring_transient = array_reverse( get_transient( 'wpc_user_activity_monitoring_transient' ), true );
                
                $recently_offline_nusers = array();
        
                foreach ( $wpc_user_activity_monitoring_transient as $user_id => $timestamp ) {
        
                    if ( $timestamp < ( current_time( 'timestamp' ) - self::USER_INACTIVITY_MARGIN ) ) {
        
                        array_push( $recently_offline_nusers, $user_id );
        
                    };
        
                };
    
                return $recently_offline_nusers;
    
            }        
    
        };
    
        $wpc_user_activity_monitoring = new WPC_User_Activity_Monitoring();
    
    };
    
    /**
     * Schedules a recurring daily event, firing at 23:59:00 to delete the WPC user activity monitoring transient.
     *
     * @since 1.0.0
     */
    if ( ! wp_next_scheduled ( 'schedule_event_delete_wpc_user_activity_monitoring_transient' ) ) {
    
        wp_schedule_event( strtotime( '23:59:00' ), 'daily', 'schedule_event_delete_wpc_user_activity_monitoring_transient' );
    
    };
    
    /**
     * Delete the WPC user activity monitoring transient.
     *
     * @since 1.0.0
     */
    add_action( 'schedule_event_delete_wpc_user_activity_monitoring_transient', 'delete_wpc_user_activity_monitoring_transient' );
    
    if ( ! function_exists( 'delete_wpc_user_activity_monitoring_transient' ) ) {
    
        function delete_wpc_user_activity_monitoring_transient() {
    
            delete_transient( 'wpc_user_activity_monitoring_transient' );
    
        };
    
    };
    

    Packaging it all in a nice plugin.

    I’ve also made a plugin for an easy implementation. It’s open source on GitHub @ https://github.com/amarinediary/WPC-User-Activity-Monitoring.
    There is additional documentations and functionalities.