首先:这个问题与Check if user is an admin by username or email only有关
第二:你的第一个块中的逻辑很奇怪......这就是应该的样子
使用 WordPress 登录工作流程
您应该始终使用内置的 WordPress 登录表单和身份验证工作流程。使用并滚动您自己的登录页面并不难,除非您做到完全正确
,否则您的应用程序
非常不安全
要使用默认的 WordPress 登录流程,请在仪表板的通用 PHP 文件中添加类似内容
<?php
require_once 'path/to/wp-load.php';
// Before every page load
if ( ! is_user_logged_in() ) {
// Not logged in at all... redirect to WP Login Page
auth_redirect();
exit(); // Exit to be safe
} elseif ( ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
wp_logout(); // Destroy their login session
wp_die('You must be an administrator'); // Die with a nice error page
}
让我解释一下这个工作流程:
首先我们导入wp-load.php。这也有点不受欢迎,可能有一种更轻松的方法,但现在它应该工作得很好
现在,假设用户加载了https://example.com/my-admin/index.php,您的common.php 将首先检查用户是否已登录。如果没有,那么它将调用auth_redirect() 并退出,这将重定向用户给https://example.com/wp-login.php?return_url=https%3A%2F%2Fexample.com%2Fmy-admin%2Findex.php
用户将使用 wp-login 页面登录,然后他们将被重定向回 https://example.com/my-admin/index.php,您的 common.php 现在会将 is_logged_in() 识别为 true...所以我们进入下一个 elseif 位置将检查用户是否是管理员。如果不是,那么它将终止他们的身份验证会话并以 wp_die 失败我们终止身份验证会话,以便如果他们重新加载页面,他们将被带回登录页面以输入管理员的凭据,并且不会重复显示 wp_die 页面,您可以随意调整它,因为这可能不是所需的行为(可能重定向到 /wp-admin/... 或在 wp_die 中为常规 /wp-admin/ 提供链接)
如果他们确实具有管理员角色,则将继续执行请求并且可以访问仪表板。
请注意,要使其正常工作,您需要让仪表板与您的 WordPress 安装在同一个域上运行...否则 cookie 将无法传输。
滚动您自己的登录页面。这是不好的做法
这很难做到...这个示例不包括 Nonce、蜜罐或任何其他您将通过标准登录表单(使用默认核心或来自其他插件)获得的安全功能
<?php
// Your login.php page
// Really, no really, this should just be done with WordPress's default login page with an auth_redirect()
// Really this is not recommended, it's really bad practice, and much less secure
// You've been warned
// If they provided a username and password, then check them
if ( isset( $_POST['username'] ) && isset( $_POST['password'] ) ) {
$username = $_POST['username']
$username = $_POST['password']
// Check the username and password with WordPress to see if they are for any user
$user = wp_authenticate( $username, $password );
$error = '';
if ( is_a( $user, 'WP_User' ) ) {
// Verify that the user is an admin
if ( in_array( 'administrator', (array) $user->roles ) ) {
// Redirect them to the dashboard
wp_redirect('dashboard.php');
exit();
} else {
$error = "Correct password, but not an Admin : (";
}
} else {
$error = "Wrong password :(";
}
}
// The Login Page
?>
<html>
<head>
<title> My Login </title>
</head>
<body>
<form action="login.php" method="POST">
<?php if ( $error ): ?>
<div class="error"><?php echo $error; ?></div>
<?php endif; ?>
<label>
Username:
<input type="text" name="username" placeholder="username" required />
</label>
<label>
Password:
<input type="password" name="password" placeholder="password" required />
</label>
</form>
</body>
</html>
在您加载除登录页面之外的任何其他页面之前,您应该拥有此代码
<?php
if ( ! is_user_logged_in() || ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
wp_redirect('login.php?error=Please%20Login');
exit();
}
// now you can do your stuff