Keep Users Based On Role Out of WP-ADMIN

Here is a quick and dirty way to keep your users out of the WP-ADMIN area.  I have not found a good way to redirect a user from the wp-login.php page to a custom page and not profile.php. (anyone knows, please let me know : > ). I needed this as i had a front end system for users to manage their profiles. That part needed to look like the regular theme and not like the admin area.

This code can be placed in your theme’s functions.php or in a plugin. You can replace “administrator” with any role that you choose.

function wp_admin_role_limiter() {
     if ( ( is_user_logged_in() ) && ( preg_match( '/wp-admin/', $_SERVER['REQUEST_URI'] ) ) ) {
          if ( !current_user_can( 'administrator' ) ) {
	       header( 'Location: http://www.domain.com/custom-profile-page/' );
	  }
     }
}
add_action( 'admin_head', 'wp_admin_role_limiter' );

4 Responses to “Keep Users Based On Role Out of WP-ADMIN”

  1. Oliver Chank

    Thanks a lot for this snippet, I really needed this. Although I got the Headers already sent error…

    I changed the “admin_head” hook for the “admin_init” one and it works like a charm now.

    I also changed the header() function to the built-in wp_redirect( home_url() ); exit; for no apparent reason, but I thought it was worth mentioning.

    :)

    Reply
    • Matthew Price

      Hi

      I am glad that it helps. It definitely solved some issues for me when i wrote it. And thanks for the revised action. i guess where i have it in my script is different and doesn’t cause the headers message, but i have definitely gotten that before.

      Matt

      Reply
    • Matthew Price

      Hi

      So i visited your blog and noticed that you wrote about Roots. Ben is a good friend of mine out here in Colorado. Glad to see international support for his project!

      Matt

      Reply

Leave a Reply