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

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...