1
votes

Trying to restrict access to admin area based on role in wordpress 3.6

Tried the following. This prevents anyone without administrator access but not my custom role "Super User". This keeps redirecting to the homepage.

function prevent_admin_access()
{
if ( false !== strpos( strtolower( $_SERVER['REQUEST_URI'] ), '/wp-admin' ) && !current_user_can( 'administrator' ) && !current_user_can( 'Super User' ) )
wp_redirect( home_url() );
}
add_action( 'init', 'prevent_admin_access', 0 );
1
Fixed it the "super user" role needed an underscore in the middle - it didnt like the space - user2903829
see my answer as to why you shouldn't do it that way - frnhr

1 Answers

1
votes

When adding the new role with add_role() you (or a plugin) defined "Role name" and "Display name for role" (http://codex.wordpress.org/Function_Reference/add_role).

current_user_can() takes name, not display name, i.e. "case-sensitive, and should be all lowercase" (see http://codex.wordpress.org/Function_Reference/current_user_can)

In your case I'm guessing that would be

... && !current_user_can( 'super_user' ) ...

EDIT:

Only now did I see you are passing a role instead of capatibility to current_user_can(). This will work (in WP 3.6 at least) but don't do that.

From the docs (links above):

Do not pass a role name to current_user_can(), as this is not guaranteed to work correctly (see #22624). Instead, you may wish to try the check user role function put together by AppThemes.

I'd suggest that you use some capability that only admins and your superusers have, probably update_core or something similar.