2

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.

3
  • What do you mean by page: is this a wordpress page or any url? Commented Jan 28, 2014 at 19:08
  • This doesnt make complete sense. If the user is logged in but not an admin, what happens?
    – user42826
    Commented Jan 28, 2014 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
    Commented Mar 12, 2015 at 18:00

2 Answers 2

3
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()

2
  • 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
    Commented Mar 7, 2015 at 4:04
  • 1
    I agree. I'm fond of current_user_can( 'manage_options' ) for this particular check, myself.
    – GhostToast
    Commented Mar 8, 2015 at 13:32
1

Alternatively you can set a page as PRIVATE and give a password for it. You get this option when you "Quick Edit" a page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.