weixin_33749242 2016-11-11 07:40 采纳率: 0%
浏览 13

wp登录反对用户角色

I'm using this code-

$info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;

    $user_signon = wp_signon( $info, false );

    if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
        echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
    }

    die();

Login is working fine.But how can i restrict a user with editor role in this function so that i can check the role and if its there then i will pass a custom error message in the json?

  • 写回答

1条回答 默认 最新

  • weixin_33724046 2016-11-11 08:07
    关注

    To restrict a specific user role, first you should check the users roles. If the users has the restricted roles, then simply don't perform login operation and through a error message, else sign-in the user by wp_signon. Here is the complete code should look like.

    $info                  = array();
    $info['user_login']    = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember']      = true;
    $user                  = get_user_by( 'login', $info['user_login'] );
    
    if ( $user && in_array( 'editor', (array) $user->roles ) ) {
      echo json_encode(array('loggedin'=>false, 'message'=>__('Editors are restricted.')));
    
    }else{
    
      $user_signon = wp_signon( $info, false );
    
      if ( is_wp_error($user_signon) ){
        echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
      } else {
        echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
      }
    
    }
    
    评论

报告相同问题?