Custom Code to Restrict WordPress Dashboard Access for Specific User Roles

Lukas K. Jan 15, 2025 User Roles and Permissions
How can I prevent certain users from seeing the admin area of my WordPress site?
What is the code snippet to restrict WordPress dashboard access for specific user roles, ensuring that only designated roles can access the admin panel?
Andy answered Jan 15, 2025

Solution to Restrict WordPress Dashboard Access

Custom Code Solution

This code redirects non-authorized users to the homepage when they try to access the WordPress admin area. Place this code in your theme's functions.php file or in a site-specific plugin:

Check user role and redirect if not authorized:

function restrict_admin_access() {
    if ( is_admin() && ! current_user_can( 'administrator' ) && ! wp_doing_ajax() ) {
        wp_redirect( home_url() );
        exit;
    }
}
add_action( 'init', 'restrict_admin_access' );

For multiple allowed roles, use this expanded version:

function restrict_admin_access() {
    // Define allowed roles
    $allowed_roles = array( 'administrator', 'editor', 'shop_manager' );
    
    // Get current user
    $user = wp_get_current_user();
    $current_user_roles = $user->roles;
    
    // Check if user has any allowed role
    $has_allowed_role = array_intersect( $allowed_roles, $current_user_roles );
    
    if ( is_admin() && ! $has_allowed_role && ! wp_doing_ajax() ) {
        wp_redirect( home_url() );
        exit;
    }
}
add_action( 'init', 'restrict_admin_access' );

To also hide the admin bar for restricted users:

function remove_admin_bar() {
    if ( ! current_user_can( 'administrator' ) ) {
        show_admin_bar( false );
    }
}
add_action( 'after_setup_theme', 'remove_admin_bar' );

Plugin Solutions

If you prefer a plugin solution, here are reliable options:

  1. User Role Editor - Offers granular control over user roles and capabilities
  2. Admin Menu Editor - Allows customization of the admin menu per user role
  3. Restrict User Access - Creates custom user levels with fine-grained access control

Additional Notes

  • The code checks if the user is trying to access the admin area (is_admin())
  • It excludes AJAX requests to prevent breaking frontend functionality
  • The multiple roles version allows you to easily modify the $allowed_roles array
  • Make sure to test thoroughly after implementation, especially if your site uses admin-ajax.php for frontend features

These solutions maintain WordPress security best practices while effectively restricting dashboard access to unauthorized users.