Restrict Admin Panel Access to Selected Roles in WordPress
Explanation
If you want to make sure only certain people can access the WordPress admin area, this code is your friend. It checks who's trying to get into the admin panel and only lets them in if they have the right role.
Here's how it works:
- The code first checks if someone is trying to access the admin area.
- It then looks at the user's role. In this case, only 'administrator' and 'editor' roles are allowed.
- If the user doesn't have one of these roles, they get sent back to the homepage.
Additionally, it hides the admin bar for users who aren't supposed to see it. This means if you're not an 'administrator' or 'editor', you won't see the admin bar at the top of the site.
To change who can access the admin area or see the admin bar, just update the roles in the code. For example, if you want 'author' to have access, add 'author' to the list of allowed roles.
Code
<?php
// Restrict WordPress admin panel access to specific user roles
function wp_dudecom_restrict_admin_access() {
// Check if the current user is trying to access the admin panel
if (is_admin()) {
// Get the current user's role
$user = wp_get_current_user();
$allowed_roles = array('administrator', 'editor'); // Define roles that are allowed access
// Check if the user has one of the allowed roles
if (!array_intersect($allowed_roles, $user->roles)) {
// Redirect users without the allowed roles to the homepage
wp_redirect(home_url());
exit;
}
}
}
add_action('admin_init', 'wp_dudecom_restrict_admin_access');
// Ensure that users without access cannot see the admin bar
function wp_dudecom_hide_admin_bar_for_non_admins() {
// Get the current user's role
$user = wp_get_current_user();
$allowed_roles = array('administrator', 'editor'); // Define roles that are allowed to see the admin bar
// Hide the admin bar for users without the allowed roles
if (!array_intersect($allowed_roles, $user->roles)) {
show_admin_bar(false);
}
}
add_action('after_setup_theme', 'wp_dudecom_hide_admin_bar_for_non_admins');
?>
Instructions
File Location: Add the code to your theme's functions.php
file or a custom plugin file.
Prerequisites: None
Implementation Steps:
- Access your WordPress dashboard.
- Navigate to Appearance > Theme Editor if you are adding the code to
functions.php
, or go to Plugins > Editor if you are using a custom plugin. - Locate and open the
functions.php
file or your custom plugin file. - Copy the provided code snippet.
- Paste the code at the end of the file.
- Save the changes.
- Test the implementation by logging in with different user roles to ensure only 'administrator' and 'editor' roles can access the admin panel and see the admin bar.
Note: If you wish to allow additional roles, modify the $allowed_roles
array in the code to include those roles.
If you need further assistance or advanced customization, consider reaching out to wp-dude.com for expert WordPress support.