I like to secure a certain page for admins. How do I check if a user is logged (and is admin)? Of their not logged in, I want to show the login module.
-
What do you mean by page: is this a wordpress page or any url? – Chittaranjan Jan 28 '14 at 19:08
-
This doesnt make complete sense. If the user is logged in but not an admin, what happens? – user42826 Jan 28 '14 at 22:59
-
@user42826 - I would assume that the user can't access the page. In my mind, that would be an error message (indicating too low of a role) or just directing somewhere else (although I'm personally not a fan of blind redirects as that is a poor user experience IMO). – butlerblog Mar 12 '15 at 18:00
if(!current_user_can('administrator')) {
wp_redirect( wp_login_url() );
}
This will redirect non-admins to login URL. Of course, logged in non-admins will be a bit confused. You'll want to run this before get_header()
-
While this does work, passing a role name (such as 'administrator') is an incorrect use of the current_user_can() function and results can be inconsistent. You should pass a capability associated with the role rather than the role name (see: codex.wordpress.org/Function_Reference/current_user_can#Notes ). – butlerblog Mar 7 '15 at 4:04
-
1I agree. I'm fond of
current_user_can( 'manage_options' )
for this particular check, myself. – GhostToast Mar 8 '15 at 13:32
Alternatively you can set a page as PRIVATE and give a password for it. You get this option when you "Quick Edit" a page.