WordPress functions.php – Execute plugin specific user online

One Trick Pony posted a great script that I’m trying to adapt to my needs.

Registration in my website is restricted. There is only one user, a editor.
The idea is to have a Chat Plugin, and it would be enabled and disabled based on if the editor is online or not, since he will be answering the chat, and if the chat is enabled and editor offline, it only consumes space.

Read More

The code:

define('EDITOR_USER_ID', 2); // your editor user ID here

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 - ($time_limit * 60)))){

      $logged_in_users[$current_user] = $current_time;

      set_transient('users_online', $logged_in_users, 1 * 60);

    }
  }
}

add_action('admin_init', 'handle_chat');

function handle_chat(){

  if(is_user_online(EDITOR_USER_ID)){

     if(!is_plugin_active('online-chat/online-chat.php'))
       activate_plugins('online-chat/online-chat.php');

     } else {

    if(is_plugin_active('online-chat/online-chat.php'))
       deactivate_plugins('online-chat/online-chat.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') - (1 * 60));
}

Issues still left: Chat enabling/disabling should be instant, without having to wait 15 minutes after editor logout/login, so I’ve decreased this value to 1

Should be init instead of admin_init, so it could be enabled in the front end. But when I change it a errors shows up:

Fatal error: Call to undefined function is_plugin_active() in /home/mgdownhill/www/wp-content/themes/criatweb/functions.php on line 412

412-> if(!is_plugin_active(‘online-chat/online-chat.php’))
activate_plugins(‘online-chat/online-chat.php’);

My question: Is there a way to make it instant, without overloading the server? I will have a lot of websites running this chat script in the same server.

Related posts

Leave a Reply