Php 如何通过id检查用户是否在WordPress中在线?
如果其他用户在线,我想在我的网站上显示在线状态。例如,如果用户A想知道用户B是否可用,我想显示一个在线标志 我知道WordPress中有一个函数名为Php 如何通过id检查用户是否在WordPress中在线?,php,wordpress,Php,Wordpress,如果其他用户在线,我想在我的网站上显示在线状态。例如,如果用户A想知道用户B是否可用,我想显示一个在线标志 我知道WordPress中有一个函数名为is\u user\u logged\u in(),但该函数仅适用于当前用户。 有没有人知道我该怎么做 这就是逻辑: if ( user_online( $user_id ) ) { return 'Online'; } else { return 'Absent'; } 您可以使用获取用户的状态。 创建一个用户在线更新函数,并将其
is\u user\u logged\u in()
,但该函数仅适用于当前用户。
有没有人知道我该怎么做
这就是逻辑:
if ( user_online( $user_id ) ) {
return 'Online';
} else {
return 'Absent';
}
您可以使用获取用户的状态。
创建一个用户在线更新函数,并将其挂接到init
。例如:
// get logged-in users
$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;
// status no need to update if user exist in the list
// and if his "last activity" was less than let's say ...15 minutes ago
$no_need_to_update = isset($logged_in_users[$user->ID])
&& $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
}
这应该在每个页面加载上运行,但是只有在需要时才会更新瞬态。如果有大量用户在线,您可能希望增加“上次活动”的时间范围以减少数据库写入,但对于大多数站点来说,15分钟已经足够了
现在,要检查用户是否在线,只需查看瞬态中的某个用户是否在线,就像上面所做的那样:
// get logged in users
$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)));
如果没有任何活动,瞬态将在30分钟后过期。但是,如果用户一直在线,它就不会过期,因此您可能希望通过将另一个函数挂接到一个或类似的程序上,定期清理该瞬态。此功能将删除旧的$logged\u-in\u用户
条目
来源:您可以使用它来获取用户的状态。
创建一个用户在线更新函数,并将其挂接到init
。例如:
// get logged-in users
$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;
// status no need to update if user exist in the list
// and if his "last activity" was less than let's say ...15 minutes ago
$no_need_to_update = isset($logged_in_users[$user->ID])
&& $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
}
这应该在每个页面加载上运行,但是只有在需要时才会更新瞬态。如果有大量用户在线,您可能希望增加“上次活动”的时间范围以减少数据库写入,但对于大多数站点来说,15分钟已经足够了
现在,要检查用户是否在线,只需查看瞬态中的某个用户是否在线,就像上面所做的那样:
// get logged in users
$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)));
如果没有任何活动,瞬态将在30分钟后过期。但是,如果用户一直在线,它就不会过期,因此您可能希望通过将另一个函数挂接到一个或类似的程序上,定期清理该瞬态。此功能将删除旧的$logged\u-in\u用户
条目
资料来源: