How to Check If One or More Users Are Logged in using Cookie in WordPress?


WordPress provides an API is_user_logged_in() to check if any user is loggin, but unfortunately, it is not directly available when you write plugins e.g. Plugins are loaded before pluggable.php which is where is_user_logged_in() is defined.

From the implementation of is_user_logged_in() you can see it is:

1
2
3
4
function is_user_logged_in() {
    $user = wp_get_current_user(); 
    return $user->exists();
}
function is_user_logged_in() {
    $user = wp_get_current_user(); 
    return $user->exists();
}

So, we can amend the function to check if a specified user has logged in.

1
2
3
4
function is_username_logged_in($username) {
    $user = wp_get_current_user(); 
    return $user->user_login == $username;  
}
function is_username_logged_in($username) {
    $user = wp_get_current_user(); 
    return $user->user_login == $username;  
}

However, the core function wp_get_current_user is still defined in pluggable.php. The following implements a function that takes an array of allowed usernames, and returns true if any allow username has logged in.

1
2
3
4
5
6
7
8
9
10
11
12
function allowedUsersLoggedIn($allowd_users) {
    if (count($_COOKIE)) {
        foreach ($_COOKIE as $key => $val) {
            if (substr($key, 0, 19) === "wordpress_logged_in") {
                if (preg_match('/^(' . implode('|', $allowed_users) . ')/', $val, $matches)) {
                    return true;
                }
            }
        }
    }
    return false;
}
function allowedUsersLoggedIn($allowd_users) {
	if (count($_COOKIE)) {
	    foreach ($_COOKIE as $key => $val) {
	        if (substr($key, 0, 19) === "wordpress_logged_in") {
	            if (preg_match('/^(' . implode('|', $allowed_users) . ')/', $val, $matches)) {
	                return true;
	            }
	        }
	    }
	}
	return false;
}

You can safely use this function anywhere, even without the WP environment. The sample use would be:

1
2
3
if (allowedUsersLoggedIn(array("helloacm", "steakovercooked")) {
  // code that only allowed users run
}
if (allowedUsersLoggedIn(array("helloacm", "steakovercooked")) {
  // code that only allowed users run
}

The principle of this function is to check the COOKIE for specified string when allowed users logged in.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
310 words
Last Post: Cloudflare and User Agent
Next Post: How to Offload Your Server by Using CloudFlare - Cache Everything?

The Permanent URL is: How to Check If One or More Users Are Logged in using Cookie in WordPress?

Leave a Reply