How to restrict dashboard access to Admins only?

How would we restrict access to the WP admin area to all users except admins?
The users on our site have their own profile pages which do all the functions they need.

So admin should be off limits to all except admins.

How to do that?

8

We can hook to the admin_init action and check if the user is an administrator by using the current_user_can() function to see if the current user can manage_options, which is something only an administrator can do.

This code, when pasted into your functions.php file, will display a message when a non-admin tries to access the dashboard:

function wpse_11244_restrict_admin() {

    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        return;
    }

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_die( __( 'You are not allowed to access this part of the site' ) );
    }
}

add_action( 'admin_init', 'wpse_11244_restrict_admin', 1 );

If you prefer, you can provide better user experience by redirecting the user to the home page instead:

function wpse_11244_restrict_admin() {

    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
        return;
    }

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_redirect( home_url() );
        exit;
    }
}

add_action( 'admin_init', 'wpse_11244_restrict_admin', 1 );

If you want to redirect the user to their profile page, replace home_url() in the code above with the link.

Leave a Comment