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:
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.
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.
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:
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) —
293 wordsLast Post: Cloudflare and User Agent
Next Post: How to Offload Your Server by Using CloudFlare - Cache Everything?