To Prevent Certain Roles from Accessing wp-admin Use Below Code
Add code to your child theme’s functions.php
file or via a plugin that allows custom functions to be added, such as the Code snippets plugin. Avoid adding custom code directly to your parent theme’s functions.php
file as this will be wiped entirely when you update the theme.
function restrict_admin_access() {
if (is_admin() && !current_user_can('administrator') && !wp_doing_ajax()) {
wp_redirect(home_url());
exit;
}
}
add_action('admin_init', 'restrict_admin_access');
This code will:
- Blocks all non-admin users from accessing the dashboard.
- Allows AJAX requests to pass through (
wp_doing_ajax()
).
Restrict Based on Role with Custom Redirects
function restrict_admin_area_by_role() {
if (is_admin() && !wp_doing_ajax()) {
$user = wp_get_current_user();
// List of roles to block
$restricted_roles = ['subscriber', 'customer', 'attendee', 'student'];
if (array_intersect($user->roles, $restricted_roles)) {
// You can customize the redirect based on role if needed
if (in_array('attendee', $user->roles)) {
wp_redirect(site_url('/download/'));
} elseif (in_array('customer', $user->roles)) {
wp_redirect(site_url('/my-account/'));
} else {
wp_redirect(home_url());
}
exit;
}
}
}
add_action('admin_init', 'restrict_admin_area_by_role');
- It’s flexible—you can add/remove restricted roles.
- It allows specific roles to be redirected to custom pages instead of just the homepage.
Create a Reusable Helper Function to check roles of user
To centralize role checking, create a helper function:
function user_has_role($role) {
$user = wp_get_current_user();
return in_array($role, (array) $user->roles);
}
Then use:
if (user_has_role('attendee')) {
wp_redirect(site_url('/download/'));
}
Preventing access to wp-admin
for certain user roles ensures:
- Better security
- Cleaner user experience
- Clear role separation
It’s a small tweak that makes a big difference for professional websites!