问题描述

对于所有的访问者,我该怎么说管理员在线?我的意思是,如果管理员在线,所有的访客,注册和没有注册,会看到这个词 “你好管理员在线… 跟我说话”…?

谢谢

最佳解决方案

这应该让你开始。我已经使用了 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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。