Only Allow Administrators to Access the WordPress Admin Area
by Bandicoot Marketing on | Posted in Tutorials | 15 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.
15 comments for “Only Allow Administrators to Access the WordPress Admin Area”