worpress login custom error message
03 Apr 2019Wordpress Plugin API/Filter Reference/login errors
1.일단 세개의 보안 플러그인에서 나오는 로긴 실패시 나오는 에러 메시지는 커스텀을 다 했다. 마지막에 비밀번호가 틀렸을시 나오는 로긴 실패 메세지를 custom 해야 했다. 방법을 찾던 중 워드프레스 코덱스에서 찾았다.
아래 코드는 워드프레스에서 로긴 에러 메세지를 커스텀 할수 있는 필터이다.
해당 코드는 여기 가면 자세히 볼수 있다.
add_filter( 'login_errors', function( $error ) {
global $errors;//전역으로 로긴에러 객체를 받아옴
$err_codes = $errors->get_error_codes();
// Invalid username.(유저네임이 틀렸을 경우)
// Default: 'ERROR: Invalid username. Lost your password?'
if ( in_array( 'invalid_username', $err_codes ) ) {
$error = 'ERROR: Invalid username.';
}
// Incorrect password.(패스워드가 틀렸을 경우)
// Default: 'ERROR: The password you entered for the username %1$s is incorrect. Lost your password?'
if ( in_array( 'incorrect_password', $err_codes ) ) {
$error = 'ERROR: The password you entered is incorrect.';
}
return $error;
} );
2.위에 나온 코드를 적용시 제대로 작동하는 것 같았으나 어드민 보안 플러그인 기능 중 워드프레스 어드민 url주소를 바꿔주는 기능을 키면 global $errors를 null로 만들어 버린다.
3.결국 아래와 같은 코드로 변경을 했다.
add_filter( 'login_errors', function( $error ) {
if ( ! empty($_POST['log']) ) {
$username = $_POST['log'];
} else {
$username = '';
}
$user = get_user_by('login', $username);
//user 정보가 있을경우만 비밀번호 체크
if($user){
//워드프레스에 패스워드 체크하는 함수를 한번 더 태움
if ( !wp_check_password( $_POST['pwd'], $user->data->user_pass, $user->ID ) ){//새로운 WP_Error 객체를 만들어 에러메시지 갱신
$errors = new WP_Error( 'incorrect_password', sprintf ('ERROR: The password you entered for the username %s is incorrect. If you lost your password, '. 'please click Lost your password and create new password.', $username));
$error = $errors->get_error_message();
}
}
return $error;
} );