自定义注册函数没有正常工作,因为is_mail和Email_eXist在不应该出现错误时不断出现错误

时间:2018-09-18 作者:Toheeb

这是我的注册功能

    $firstname = sanitize_text_field( $_POST[\'firstname\'] );
    $lastname = sanitize_text_field( $_POST[\'lastname\'] );
    $username = sanitize_text_field( $_POST[\'reg-username\'] );
    $user_pass = sanitize_text_field( $_POST[\'reg-password\'] );
    $pass_confirm = sanitize_text_field( $_POST[\'confirm_password\'] );
    $gender = sanitize_text_field( $_POST[\'gender\'] );
    $email = sanitize_text_field( $_POST[\'email\'] );
    //Add usernames we don\'t want used
    $invalid_usernames = array( \'admin\' );
    $errors = array();
    //Do username validation
    $username = sanitize_user( $username );
    if ( empty( $username ) || validate_username( $username ) === false || in_array( $username, $invalid_usernames ) === false ) {
        $errors[]= \'Username is invalid.\';
    }
    if ( username_exists( $username ) === false) {
        $errors[]= \'Username already exists.\';
    }
    //Do e-mail address validation
    if ( !is_email( $email ) ) {
        $errors[] = \'E-mail address is invalid.\';
    }
    if (email_exists($email) === false) {
        $errors[] = \'E-mail address is already in use.\';
    }
    if ($user_pass != $pass_confirm) {
        $errors[] = \'Password combination incorrect.\';
    }
    $genders = array(\'male\',\'female\',true);
    if ( in_array( $gender,$genders )  === false){
        $errors[] = \'Invalid gender\';
    }

    //Everything has been validated, proceed with creating the user

    //Create the user
    if(!empty($errors)):
        wp_send_json_error($errors);
    endif;

    //$user_pass = wp_generate_password();
    $user = array(
        \'user_login\' => $username,
        \'user_pass\' => $user_pass,
        \'first_name\' => $firstname,
        \'last_name\' => $lastname,
        \'user_email\' => $email,
        \'gender\' => $gender
        );
    $user_id = wp_insert_user( $user );

    /*Send e-mail to admin and new user - 
    You could create your own e-mail instead of using this function*/
    wp_new_user_notification( $user_id, $user_pass );
    wp_send_json_success($user_id);
我每次都会遇到这个错误。0:"Username is invalid." 1:"Username already exists." 2:"E-mail address is invalid." 3:"E-mail address is already in use." 4:"Invalid gender" 即使所有输入都正确

即使密码组合不正确,密码确认功能也不起作用。

1 个回复
最合适的回答,由SO网友:Breus 整理而成

因为缺乏背景,我无法解决你所有的问题。我看到的一个错误是,在您的代码中,这一行:

if (email_exists($email) === false) {
    $errors[] = \'E-mail address is already in use.\';
}
必须是:

if(email_exists($email)){ etc.
因为您检查email\\u exists函数是否在其存在(翻译为true)或不存在时返回ID,这将给出false。你能为你剩下的问题提供更多的上下文(例如HTML格式的表单)吗?

编辑:你犯了同样的错误username_exists($username) === false 应该是if(username_exists($username)) 相反同样的逻辑也适用。

编辑:哦,实际上你犯的错误更多。还具有in_array( $username, $invalid_usernames ) === false 必须是:in_array( $username, $invalid_usernames ) 现在你正在检查与你想检查的完全相反的东西,我想。

结束

相关推荐