对于忘记注册的用户名这种情况,可谓再常见不过了……幸运的是,您可以在登录界面增加一个“使用Email登录”的选项,这样,我们可爱的用户应该不会再为登录不上 WordPress 而苦恼了吧?
代码添加 Email 登录功能,添加以下代码至 Functions.php:
- //remove wordpress authentication
- remove_filter(‘authenticate’, ‘wp_authenticate_username_password’, 20);
- add_filter(‘authenticate’, function($user, $email, $password){
- //Check for empty fields
- if(empty($email) || empty ($password)){
- //create new error object and add errors to it.
- $error = new WP_Error();
- if(empty($email)){ //No email
- $error->add(’empty_username’, __(‘<strong>ERROR</strong>: Email field is empty.’));
- }
- else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
- $error->add(‘invalid_username’, __(‘<strong>ERROR</strong>: Email is invalid.’));
- }
- if(empty($password)){ //No password
- $error->add(’empty_password’, __(‘<strong>ERROR</strong>: Password field is empty.’));
- }
- return $error;
- }
- //Check if user exists in WordPress database
- $user = get_user_by(’email’, $email);
- //bad email
- if(!$user){
- $error = new WP_Error();
- $error->add(‘invalid’, __(‘<strong>ERROR</strong>: Either the email or password you entered is invalid.’));
- return $error;
- }
- else{ //check password
- if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
- $error = new WP_Error();
- $error->add(‘invalid’, __(‘<strong>ERROR</strong>: Either the email or password you entered is invalid.’));
- return $error;
- }else{
- return $user; //passed
- }
- }
- }, 20, 3);
- 本文固定链接: https://freekk.cn/6333.html
- 转载请注明: 漱石 于 最后的面包 发表
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!
Pingback 引用通告: WordPress 实现用户使用Email地址登录-MTPAN资源福利分享