問題描述

對於所有的訪問者,我該怎麼説管理員在線?我的意思是,如果管理員在線,所有的訪客,註冊和沒有註冊,會看到這個詞 「你好管理員在線… 跟我説話」…?

謝謝

最佳解決方案

這應該讓你開始。我已經使用了 5 分鐘的超時時間,讓時間閒置在網站上。您可以使用腳本提高準確性 (如果當前用户是管理員)& 每幾分鐘 ping 一次 AJAX 請求,以更新 admin_last_seen 時間戳。

/**
 * Check if the admin was last online at least 5 minutes ago.
 * 
 * @return bool
 */
function wpse_140253_is_admin_online() {
    if ( false === $last_seen = get_option( 'admin_last_seen' ) )
        update_option( 'admin_last_seen', $last_seen = 0 );
    elseif ( $last_seen )
        return $last_seen + 5 * MINUTE_IN_SECONDS > time();
    return false;
}

/**
 * Update "admin_last_seen" timestamp.
 * 
 * @link http://wordpress.stackexchange.com/q/140253/1685
 */
function wpse_140253_update_admin_online_status() {
    if ( current_user_can( 'manage_options' ) /* Might be better to check user ID if you have multiple admins */ ) {
        if ( ! $last_seen = get_option( 'admin_last_seen' ) )
            $last_seen = 0;

        // Only make a database update if last seen greater than timeout.
        if ( $last_seen + 5 * MINUTE_IN_SECONDS < time() )
            update_option( 'admin_last_seen', time() ); 
    }       
}

add_action( 'init', 'wpse_140253_update_admin_online_status' );

並在使用中:

<?php if ( wpse_140253_is_admin_online() ) : ?>
     <div class="message">Admin is online!</div>
<?php endif ?>

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。