Ever needed to block the admin area from all users that are not administrators? This snippet will redirect all users that are not administrators back to the primary domain when they try to access the WordPress admin.
Instructions
All you have to do is add this code to your theme’s functions.php file or in a site-specific plugin:
add_action( 'init', 'blockusers_wps_init' ); function blockusers_wps_init() { if ( is_admin() && ! current_user_can( 'administrator' ) ) { wp_redirect( home_url() ); exit; } }
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out How to Easily Back Up Your WordPress Site (Step by Step).
Thanks for sharing ! Awesome snippet but it cause problem with ninja form plugin when you want to sent an email ! Any tip for that ?
Wouldnt this block ajax that uses no_priv or any type of ajax?
I want author to be able to access to that page instead of just an admin (I know the code, but needs help appending it). Also is it possible to only access posts and media only?
if you look at current_user_can and change the capability to something else if will allow other roles to access. View this page on wordpress codex to see what can be done,
http://codex.wordpress.org/Roles_and_Capabilities
Thanks. Is there a code that can append admin Like “if admin and author can” or something like that?
anything an author can an admin can so allowing authors will also allow admins.