How to check if username exist in WordPress registration

Home / Tutorials / Core / How to check if username exist in WordPress registration

How to check if username exist in WordPress registration

This quick tutorial will show you how to create a username indicator on the WordPress Registration Form. This tutorial will use AJAX and some basic WP actions to accomplish this feature.

Introduction

wp-registration-form

The image above is the registration form that we will be adding the indication to. Typically, you can find this by going to www.yoursite.com/wp-login.php?action=register. You will notice that this file does not use the WordPress theme, in fact it is a separate PHP file called wp-login.php. In order to to add to this page, we will be using the action login_footer. We will use this action to add some javascript and css to the page, add the following to your plugin file.

If you are not sure how to create a plugin, read this post.

 

The first line add_action(‘login_footer’,’mpl_add_js_login’); is used to add to the footer of the wp-login page.

In the function mpl_add_js_login we are adding some CSS, including jQuery library and an AJAX jQuery script. The jQuery script works by triggering the function when the Username field is changed. In the event that it is changed our script will take the value of the username field and submit it using AJAX to a WordPress AJAX action which will then check if username exists. The result of the AJAX request will be appended below the username field and styled using the CSS that was previously added.

WordPress Ajax Function

In this section, we are going to write the script that checks if the username exists and sends a response. Add the following snippet to your plugin.

 

In the first two lines of the snippet, we are creating the ajax functions so WordPress can recognize them when the are called. In the callback function we first create an array that will hold the response to be returned and we sanitize the data passed through the AJAX request for security reasons, then we use the function username_exists to check if username exists. Based on whether it exists or not, we add the status and text to our response array and use json_encode to response in JSON format.

One the response is received successfully, the jQuery script will append a div with the uname_status and add new class to it based on the AJAX response status, this will style the div contents. The response will also add the text into the div.

Results

Now, let’s try it out and see if it works.

Recent Posts
Contact Us

We're not around right now. But you can send us an email and we'll get back to you, asap.

Not readable? Change text. captcha txt

Start typing and press Enter to search