我的问题是,我无法验证是否有用户将现有电子邮件插入AJAX注册表。然而,我的表单工作正常,它正在注册用户,并给出所有其他错误,如“无效电子邮件”或“空字段”。唯一没有破坏的是the error for the existing emails.
function ajax_register(){
// First check the nonce, if it fails the function will break
check_ajax_referer( \'ajax-register-nonce\', \'security\' );
$user_login = $_POST[\'user_login\'];
$sanitized_user_login = sanitize_user( $user_login );
$user_email = $_POST[\'user_email\'];
$user_pass = wp_generate_password( 12, false);
$user_tp = $_POST[\'user_tp\'];
if(empty($user_tp)) $capa = \'subscriber\';
else $capa = $user_tp;
//Adding errors
$newerrors = my_errors($user_email);
//CREATE USERS
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if (is_wp_error($user_id)){
//VERIFYNG WITH DEFAULT ERRORS
} elseif (is_wp_error($newerrors)){
//VERIFYING WITH MY CUSTOM ERRORS
echo json_encode(array(\'loggedin\'=>false, \'message\'=>__($newerrors->get_error_message())));
} else {
//REGISTER USERS
}
die();
}
//MY CUSTOM ERROR FUNCTION
function my_errors($user_email) {
$errors = new WP_Error();
$user_email = apply_filters( \'user_registration_email\', $user_email );
if ( $user_email == \'\' ) {
$errors->add( \'empty_email\', __( \'Please, insert your email.\') );
} elseif ( ! is_email( $user_email ) ) {
$errors->add( \'invalid_email\', __( \'The email is not valid.\') );
$user_email = \'\';
//THIS IS WHERE I CHECK THE EXISTING EMAIL ***
} elseif ( email_exists( $user_email ) ) {
$errors->add( \'registered\', __( \'This email is already registered.\' ) );
}
if ($errors->get_error_code())
return $errors;
}
***此时,我验证
$user_email 已存在。但是当我测试它时,消息没有显示,表单被卡住了。
是否需要add_action? 你能解释一下我哪里错了吗?谢谢
最合适的回答,由SO网友:TheDeadMedic 整理而成
你为什么要自己努力工作?wp_create_user 已检查电子邮件/登录是否存在,这也是您的代码“失败”的原因-$user_id 将已经是WP_Error, 所以你的elseif ( is_wp_error( $newerrors ) ) 切勿开火。
您只需要:
$user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email, $capa );
if ( is_wp_error( $user_id ) ) {
wp_send_json( array(
\'loggedin\' => false,
\'message\' => $user_id->get_error_message(),
) );
}
exit;
还请注意,我使用了WordPress助手
wp_send_json, 这是将JSON数据发送回客户端的正确方法。