WordPress Restrict Access to Admin Area based on Role

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 );

Related posts

Leave a Reply

1 comment

  1. 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):

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