我需要显示每个作者页面(自定义作者页面模板)的在线状态(在线/离线)。
is_user_logged_in()仅适用于当前用户,我找不到针对当前作者的相关方法,例如is_author_logged_in()
有任何想法吗?
回答
一个Trick Pony非常友善,可以使用瞬态为两到三个函数准备编码,这是我以前从未使用过的。
http://codex.wordpress.org/Transients_API
将此添加到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);
}
}
}
将此添加到author.php(或另一个页面模板):
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.';}
第二答案(请勿使用)
此答案仅供参考。正如One Trick Pony指出的那样,这是不受欢迎的方法,因为数据库在每次页面加载时都会更新。经过进一步的审查,该代码似乎只是在检测当前用户的登录状态,而不是与当前作者进行额外匹配。
1)安装此插件:http : //wordpress.org/extend/plugins/who-is-online/
2)将以下内容添加到页面模板:
//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>";
}