How to restrict dashboard access to Admins only?

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