13

I'd like to prevent certain user roles from accessing the dashboard http://www.openeye.net/wp-admin/ at all. I've moved and restyled user profiles to a new page that's viewable on the site. How would I go about doing this?

1
  • I requested WooCommerce to change their setup, so it is possible to manage authorisations for their part of the menu. The idea needs votes on: https://ideas.woocommerce.com Please give it your maximum 3 points, thanks!
    – Stefan
    Nov 21, 2019 at 7:55

4 Answers 4

25

To lock subscribers and contributors out of the admin:

function wpse23007_redirect(){
  if( is_admin() && !defined('DOING_AJAX') && ( current_user_can('subscriber') || current_user_can('contributor') ) ){
    wp_redirect(home_url());
    exit;
  }
}
add_action('init','wpse23007_redirect');

Hope that helps. All roles give the user a capability that is the name of that role, so you can use any role name as a capability.

7
  • Excellent, however I'm getting a syntax error on the second line. Jul 14, 2011 at 21:23
  • Oh ok it's related to the extra ( after ('DOING_AJAX') Jul 14, 2011 at 21:58
  • Oh, sorry; that was intentional. There was supposed to be another one closing at the end. I added it to the answer. Jul 15, 2011 at 15:06
  • Is there a reason this doesn't work with the 2011 theme and the members plugin? Sep 9, 2011 at 6:36
  • 1
    This doesn't seem to work on network sites, any idea why? Oct 9, 2011 at 21:59
3
//If User Roll is Subscriber, It can not login in Dashboard 
function wpse23007_redirect()
{
    if( is_admin() && !defined('DOING_AJAX') && current_user_can('subscriber') )
    {
        wp_logout();
        wp_redirect(home_url());
        exit;
    }
}
add_action('init','wpse23007_redirect');
1

Yes, you would need to use the current_user_can( $capability ) function. Here is the official WordPress reference: https://codex.wordpress.org/Function_Reference/current_user_can

0
 add_action('init', function(){

      $redirect = isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : home_url( '/' );
      $user = wp_get_current_user();
      if ( !defined('DOING_AJAX') && in_array( 'subscriber', (array) $user->roles ) ) {

          wp_redirect($redirect);
          exit();
      }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.