WordPress 提供了一个方法 is_user_logged_in() 用于检查用户是否是登陆状态. 但是很可惜 这个方法在 pluggable.php 中定义. 也就是说如果你需要在插件中使用, 那么这个函数是没有被定义的.
我们来看一下 is_user_logged_in() 的实现:
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(); }
我们可以改一下, 用于检查指定的用户名是否登陆.
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; }
当然 wp_get_current_user 这个方法 也是定义在 pluggable.php 文件中 这样一来就不是很方便了. 以下有一个解决方法 是检查 COOKIE中是否有白名单用户的信息.
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; }
这种方法好处是可以把代码放在任意的 PHP 中而不需要依赖WP的运行环境. 使用方法如:
1 2 3 | if (allowedUsersLoggedIn(array("justyy", "codingforspeed")) { // 只有以上两个用户其中一人登陆的情况下才执行. } |
if (allowedUsersLoggedIn(array("justyy", "codingforspeed")) { // 只有以上两个用户其中一人登陆的情况下才执行. }
英文: How to Check If One or More Users Are Logged in using Cookie in WordPress?
强烈推荐
- 英国代购-畅购英伦
- TopCashBack 返现 (英国购物必备, 积少成多, 我2年来一共得了3000多英镑)
- Quidco 返现 (也是很不错的英国返现网站, 返现率高)
- 注册就送10美元, 免费使用2个月的 DigitalOcean 云主机(性价比超高, 每月只需5美元)
- 注册就送10美元, 免费使用4个月的 Vultr 云主机(性价比超高, 每月只需2.5美元)
- 注册就送10美元, 免费使用2个月的 阿里 云主机(性价比超高, 每月只需4.5美元)
- 注册就送20美元, 免费使用4个月的 Linode 云主机(性价比超高, 每月只需5美元) (折扣码: PodCastInit2022)
- PlusNet 英国光纤(超快, 超划算! 用户名 doctorlai)
- 刷了美国运通信用卡一年得到的积分 换了 485英镑
- 注册就送50英镑 – 英国最便宜最划算的电气提供商
- 能把比特币莱特币变现的银行卡! 不需要手续费就可以把虚拟货币法币兑换
微信公众号: 小赖子的英国生活和资讯 JustYYUK