H.Norman H.Norman -4 years ago 63
SQL Question

Wordpress/PHP - options for showing user that chosen username is taken

I have a wordpress site where I've created a custom HTML registration form. I"m using PHP in the functions file that creates the user in our WP users table and emails us with the info from the form. Everything works great, but we want a new way of showing the customer if the username is taken. I have it currently working, we're testing it with the username testUser which exists. If we try to register with it and hit submit, it goes to an index page that says it already exists and then redirects the customer back to the form to fix it. We'd like to have an option that lets the customer know this before even submitting, but I'm a novice with AJAX calls and I've had troubles. I'm hoping there's another way. This is the current snippet of working code:

if (username_exists($user)){

echo 'Username already exists. Please wait while we redirect you back to the form';
die("<meta http-equiv=\"refresh\" content=\"5;url=".$_SERVER['HTTP_REFERER']."\"/>");


}

if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
if( !is_wp_error($user_id) ) {
//user has been created
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );

wp_mail( $to, $email_subject, $message, $headers);


//Redirect
wp_redirect( 'http://www.dev.smithhonig.com/thank-you' );
exit;
} else {
//$user_id is a WP_Error object. Manage the error
}
}


}
add_action('init','create_account');

Answer Source

To show a user that username is already taken or available you do need to make an ajax call with the desired username the user is typing.. the steps to do this will be like

  1. Detect when there is a change in text field used to enter username in your registration form.
  2. Send ajax request to check if the typed username is available.
  3. Check response of ajax call.
  4. Show a message to user if username is available or not.

Place this code in functions.php of your theme

add_action( 'wp_ajax_verify_username', 'check_username' );
add_action( 'wp_ajax_nopriv_verify_username', 'check_username' );
function check_username(){
    $username = $_POST['username'];
    if( username_exists( $username ) ) {
        echo $username . ' already taken.';
    }else {
        echo 'Hurray ' . $username . ' is available.';
    }

    exit;
}

the add_action('wp_ajax_verify_username', 'check_username') will add a hook that checks if an ajax call is made with action parameter set as verify_username, if so, it'll be handled by the function check_username in your functions.php which we've written below the hook.

check_username function checks the value of username variable sent with the ajax call and checks if the username already exists using WP function username_exists() and then prints the appropriate response for ajax call.

The ajax call can be made using the following code:

jQuery(document).ready(function(){
    jQuery('#username').on('change', function(){
        let user = jQuery(this).val();
        jQuery.ajax({
            type: 'POST',
            url: '<WP_AJAX_URL_HERE>',
            data: {action: 'verify_username', username: user},
            success: function(data){
                console.log(data);
                // Write code to show the message to user here
            },
            error: function(err){
                console.log(err);
            }
        });
    });
});

Replace the <WP_AJAX_URL_HERE> with your websites admin-ajax.php url

Hope that helps. Let me know if you need more explanation. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download