S
S
sputnickk2020-04-16 09:43:14
WordPress
sputnickk, 2020-04-16 09:43:14

How to disable login to an account by role?

Hello! Guys, tell me what's wrong, I need to restrict login to the account for simple customers (role), here's the code:

//вот тут пробую разные варианты, но не работает
add_filter('authenticate',function($user,$username) {
    if (!is_wp_error($user)) {
        $auth_user=get_user_by('login',$username);
        if ($auth_user &&  !is_user_role_in( array('administrator','dropshipper') )  ) {
            return new WP_Error('authentication_failed', '<p class="message"><b>Личный кабинет отключен. Покупки осуществляются без регистрации.</b></p>');
        }
    }
    return $user;
},100,2);

 
 

## Проверяет есть ли указанная роль в ролях текущего/указанного пользователя
## $roles строка/массив - название роли которую нужно проверить у текущего пользователя
/*
// Пример использования
if( is_user_role_in( array('new_role','new_role2') ))
  
  echo 'Роль текущего пользователя new_role или new_role2';
*/
function is_user_role_in( $roles, $user = false ){
  if( ! $user )           $user = wp_get_current_user();
  if( is_numeric($user) ) $user = get_userdata( $user );

  if( empty($user->ID) )
    return false;

  foreach( (array) $roles as $role )
    if( isset($user->caps[ $role ]) || in_array($role, $user->roles) )
      return true;

  return false;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Brumer, 2020-04-16
@sputnickk

add_filter('authenticate','filter_function_name_4601');
function filter_function_name_4601($user){
  if(isset($_POST['log'])){
  $username=$_POST['log'];
  if(isset($username)){$user=get_user_by('login',$username);$user_data=get_object_vars($user);}	
  if(isset($user_data)){$userId=$user_data["ID"];$u_meta=get_userdata($userId);$u_roles=$u_meta->roles;}
  }	
  if(!empty($u_roles)&&(in_array('administrator',$u_roles,true)||in_array('editor',$u_roles,true))){//перебираем роли. которые хотим запретить
  $Who=in_array('administrator',$u_roles,true)?__('Администраторам','VAB'):__('Редакторам','VAB');
  wp_die($Who.' '.__('авторизация запрещена','VAB'));//пишем месседж для них
  }else{
  return $user;
  }
}

Result, depending on who breaks
5e9849612ddb8834465415.jpeg
5e9849ed43f95972809011.jpeg

via username
add_filter('authenticate','filter_function_name_4601',10,3);
function filter_function_name_4601($user,$username,$password){
  if($username){
  if(isset($username)){$user=get_user_by('login',$username);$user_data=get_object_vars($user);}	
  if(isset($user_data)){$userId=$user_data["ID"];$u_meta=get_userdata($userId);$u_roles=$u_meta->roles;}
  }	
  if(!empty($u_roles)&&(in_array('administrator',$u_roles,true)||in_array('editor',$u_roles,true))){//перебираем роли. которые хотим запретить
  $Who=in_array('administrator',$u_roles,true)?__('Администраторам','VAB'):__('Редакторам','VAB');
  wp_die($Who.' '.__('авторизация запрещена','VAB'));//пишем месседж для них
  }else{
  return $user;
  }
}

this is if the developers change the log tomorrow to something else...

A
Anton, 2020-04-16
Veida @aveyda7

Option one: using the Remove Dashboard Access plugin. You can download it here: https://wordpress.org/plugins/remove-dashboard-acc...
Option two: Add the following code to your active theme's functions.php file. Instead of administrator, insert the role you need. A user who tries to log into the WordPress admin panel will receive a 404 error message.

function true_wp_admin_block() {
  if (!current_user_can('administrator')) { // если не администратор
    header('HTTP/1.0 404 Not Found');
    exit();
  }	
}
add_action('admin_menu', 'true_wp_admin_block');

There are already 6 user groups in WordPress by default:
  1. Super Admin is a super administrator who has the right to manage a network of sites.
  2. Administrator - administrator.
  3. Editor - editor, can publish and edit posts of other users.
  4. Author - the author can publish and edit their own posts.
  5. Contributor - a participant, can write and send his posts for moderation.
  6. Subscriber is a subscriber, all he can do is edit his profile.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question