Only Allow Administrators to Access the WordPress Admin Area
by c.bavota | Posted in Tutorials | 11 comments
A while back I wrote a quick tutorial about fixing an issue with the user redirect called “Redirect After Adding a New User in WordPress”. In that tutorial, I mentioned using the wp_redirect() function to get you to the profile page after adding a new user, which would help speed up the process of modifying a user’s settings.
In this tutorial, I’m going to use that same function to redirect users away from the WordPress admin area, unless of course they’re administrators. All you need to do is hook into the admin_init action:
add_action( 'admin_init', 'redirect_non_admin_users' );
/**
* Redirect non-admin users to home page
*
* This function is attached to the 'admin_init' action hook.
*/
function redirect_non_admin_users() {
if ( ! current_user_can( 'manage_options' ) && '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ) {
wp_redirect( home_url() );
exit;
}
}
The conditional to check if a user isn’t an admin first sees if they can manage options (see WordPress Roles and Capabilities) then it makes sure that the call isn’t trying to access the Ajax file to actually perform an Ajax call. If both are true, it redirects the user to the home page using the home_url() function.
Placing the above code in your theme’s functions.php file will add the ability to redirect non-admin users away from your WordPress admin and keep that area safe from those who might wish to do some mischief.



Is there any way I can prevent my admin folders from being indexed?
You would have to look into creating a robot.txt file to tell search engines to not index that folder.
@c.bavota, thanks for this! Im using something like this to keep non-admins out of the dashboard, but I have Contributors doing some front-end post creation and editing, and a ‘delete post’ function is not working when this redirect function is enabled.
Any idea how to allow this type of request through for Contributors but still disallow them to visit the dashboard and other admin pages? Thanks!!
The best way to avoid that would be to either use Ajax to delete posts or write a front end function that mimics the backend one. Otherwise, you would have to open up parts of your admin which in turn might allow non-admins to access them.
Thanks @c.bavota! I got it figured out.
Very helpful!!
Thanks for sharing
very useful, as it says, admin should really only be for admin use / users.
Thank you. You save my life. I must customize one feature to secure content by member groups. This is useful for me.
Now i’ve applied some setting to my wp blog. Thanks
Nice one, thanks you!
Thanks for sharing, really helpful.