I am creating an admin section from scratch. The users for this should be users from a wordpress site where they have administrator privileges. So I am currently authenticating the users using
if( (!user_pass_ok($user, $pass)){
//login fail
}else{
//successful login
}
But I also want to know if the user is an administrator. What I came across by looking online is they use the current_user_can( 'administrator' )
. But in my case, the user has not yet logged in. All I have to check if the user is an admin, is the username/email address the user enters for login. How can I check if this user is an admin by only the username/email?
As I noted in a comment
user_pass_ok( $user, $pass )
is deprecated in favor of wp_authenticate.Additionally, WordPress has an amazing Capabilities API that goes far beyond Roles. I would strongly recommend reading up on it.
For a brief example, if I wanted to grant a user access to manage WordPress options (a capability called
manage_options
that is inherited from the Administrator role), all I have to do is saycurrent_user_can('manage_options')
or use theWP_User->has_cap(...)
function.Matching based on capabilities is usually much more flexible that matching on a Role... for example imagine my site had a second role called "Developers". If you gated access based on roles, and you wanted to give users in the developer role access to your feature, you would need to add a second check whenever you need to verify a users permissions:
($role == 'administrator' || $role == 'developer')
So, if you have a user logged in already then you can always verify their capabilities with:
or define your own custom cap, give it to all administrators:
and check the custom cap against the current user
The added benefit to capabilities is that WordPress will automatically check the current user's permissions when rendering the WP Admin menu if you register your admin section with one of the add_*_page functions (add_menu_page()) and a capability like 'manage_options'
Lastly, It was a bit unclear as to whether you were logging in users yourself, if so I would propose this alternative if you are logging in the user from scratch (i.e. not using WordPress's login form):
You will also need to call
current_user_can( 'manage_options' )
during every page load of your custom admin to verify that the user is logged in and has permissions, if that fails, then direct them to your custom login page... or possibly, the wordpress login page with auth_redirect().