As a website owner utilizing the powerful WordPress content management system, you understand the significance of maintaining a secure admin dashboard. This is where crucial site management tasks take place, and it’s essential to limit access to authorized individuals even if their user role already all the actions.
With the following code snippet, you can restrict access to the WordPress admin dashboard based on user roles. By implementing this code, you get subscribers (and other low-level user roles) completely out of the dashboard)
function redirect_user_role() { if(!defined('DOING_AJAX')) { $current_user = wp_get_current_user(); foreach($current_user->roles as $role_name) { if ($role_name == 'user_role') { wp_redirect( 'https://example.com/path' ); exit(); } } } } add_action( 'admin_init', 'redirect_user_role' );
Code explanation
The provided code snippet focuses on restricting access to the WordPress admin dashboard for a specific user role. Let’s dive into the code to understand how you can implement this and also modify it in your needs.
To begin, we write a function called “redirect_user_role” and hook it into the “admin_init” action. This action is triggered when the admin dashboard is initialized, ensuring that the code executes at the appropriate time.
Within the function, the code performs a check to ensure that it is not executed during AJAX requests. This precautionary step prevents any interference with AJAX-based functionalities.
Next, the code retrieves information about the current user using the wp_get_current_user()
function provided by WordPress. After that the code iterates through each user role stored in the $current_user->roles
array.
During each iteration, the code compares the current role ($role_name
) with the desired role, in this case, “user_role”. This condition serves as the basis for determining who should be redirected away from the admin dashboard.
If a match is found, the code triggers the wp_redirect()
function. This function accepts the URL of a designated path as an argument. Here, you have the freedom to choose a path where users with the “user_role” will be redirected, effectively preventing them from accessing the WordPress admin dashboard.
Then immediately after redirect we run exit()
function. This immediate termination of the script execution ensures that no further code is processed after the redirection.