簡體   English   中英

如何通過用戶ID檢查WordPress是否在線?

[英]How can I check if a user is online in WordPress by his id?

如果其他用戶在線,我想在我的網站上顯示在線狀態。 因此,例如,如果用戶A想知道用戶B是否可用,我想顯示一個在線標志。

我知道WordPress中有一個名為is_user_logged_in()的函數,但該函數僅適用於當前用戶。 https://developer.wordpress.org/reference/functions/is_user_logged_in/有沒有人知道如何完成此工作?

這是邏輯:

if ( user_online( $user_id ) ) {
    return 'Online';
} else {
    return 'Absent';
}

您可以使用Transients API來獲取用戶的狀態。 創建一個您掛在init上的user-online-update函數。 例如:

// 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_in_users條目...

資料來源: https : //wordpress.stackexchange.com/a/34434

    First get the user id of the user B by 

    $user_id_B = get_current_user_id();

    Now here give the condition for the particular user B to check whether he is online or not

if(is_user_logged_in()){
    if( $user_id_B == 'user id of B')
    {
        return 'Online'; (or echo 'online';)
    }
}
By this you will get the presence of user B.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM