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()
Any ideas?
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 (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>";
}