In this AJAX login articles series we will implement best-practice techniques to provide Ajax login/logout mechanism for WordPress that will be available in sidebar.
UPDATE: I have created another article to do AJAX Login and Register in a popup box. You should give it a try.
By following this article you will be able to create a nice login box that resides in widget sidebar of your website and checks for user credentials and behaves accordingly.
AJAX login – HTML markup
First of all we need to create a login form in our page’s sidebar. To do this open your WordPress admin widgets page, drag a text widget to your desired sidebar, copy and paste the following code:
1 2 3 4 5 6 7 8 9 10 | <div id="divlogin"> <form id="login" action="login" method="post"> [xyz-ips snippet="ajaxLogin"] <p class="status"></p> <p><input type="text" class="form-control required" placeholder="User Name" name="username" id="username"></p> <p><input type="text" class="form-control required" placeholder="Password" name="password" id="password"></p> <p><input name="" value="LOGIN »" type="submit"></p> </form> </div> <div id="divuser"></div> |
Notice at line number 3 in the above code, there is [xyz-ips snippet="ajaxLogin"]
shortcode used. Actually we need to call ‘wp_nonce_field’ function which creates a hidden field with ID “security” and value “ajax-login-nonce” in hashed form. We must use and run php script in widget to achieve this.
You can use any plugin of your choice which creates shortcode to let you run the following php script in widget:
1 2 3 | <?php wp_nonce_field('ajax-login-nonce','security'); ?> |
div #divuser at line number 10 will let us show display name of logged in user and a logout link after successful login. Save the widget and check your page.
You will find login form ready there and also inspect element or view it’s source that would be something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <div id="divlogin"> <form id="login" method="post" action="login"> <input id="security" type="hidden" value="xxxxxxxxxx" name="security"> <input type="hidden" value="YOUR_URL" name="_wp_http_referer"> <p class="status"></p> <p> <input id="username" class="form-control required" type="text" name="username" placeholder="User Name"> </p> <p> <input id="password" class="form-control required" type="text" name="password" placeholder="Password"> </p> <p> <input type="submit" value="LOGIN »" name=""> </p> </form> </div> <div id="divuser" style="display: none;"> </div> |
Validating and sending user info via AJAX
When the user fills out the form and clicks LOGIN
, client side validation is done to ensure that data is filled up in required format and sent to the server.
The script checks if the inserted data is correct and, based on the fact , notifies the user that the login was successful and performs the login and replaces the form with user display name and a logout link, or just notifies him that his data is incorrect.
All of the server-side checking code will be placed inside of theme’s functions.php file. We’ll create a function that will include our JS files, create a new JS object called ajax_login_object and enable the not logged in users to call our function. So open your theme’s functions.php file and place the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // AJAX Login function ajax_login_init(){ wp_register_script('ajax-validate-script', get_template_directory_uri() . '/js/jquery.validate.js', array('jquery') ); wp_register_script('ajax-login-script', get_template_directory_uri() . '/js/ajax-login-script.js', array('jquery') ); wp_enqueue_script('ajax-validate-script'); wp_enqueue_script('ajax-login-script'); wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'redirecturl' => home_url(), 'loadingmessage' => __('Sending user info, please wait...') )); // Enable the user with no privileges to run ajax_login() in AJAX add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' ); } // Execute the action only if the user isn't logged in if (!is_user_logged_in()) { add_action('init', 'ajax_login_init'); } |
We have enqueued jquery.validate.js
to validate our form. The ajax-login-script.js
file performs AJAX login on form submit and change widget title to “Logged In” after successful login. Both files are available for download at end of this article and must be put inside js
folder under your theme directory.
The wp_ajax_nopriv_ajaxlogin
hook ensures that only users with no privileges (not logged in) can access the function ajax_login
which we will add next in functions.php.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function ajax_login(){ // First check the nonce, if it fails the function will break check_ajax_referer( 'ajax-login-nonce', 'security' ); // Nonce is checked, get the POST data and sign user on $info = array(); $info['user_login'] = $_POST['username']; $info['user_password'] = $_POST['password']; $info['remember'] = true; $user_signon = wp_signon( $info, false ); if ( is_wp_error($user_signon) ){ echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.'))); } else { wp_set_current_user($user_signon->ID); echo json_encode(array('loggedin'=>true,'username'=> $user_signon->display_name, 'message'=>__('Login successful, redirecting...'), 'logoutURL' => wp_logout_url( home_url() ))); } die(); } |
All that’s left is making the “LOGIN” button show our form and sending the form data with AJAX to the function above. To accomplish download the zip, unzip and place jquery.validate.js
and ajax-login-script.js
files inside js folder under your theme directory.
Styling
You can add style rules to your theme’s CSS file. For example: I have used the following CSS rule to show error when validation fails:
1 2 3 4 | label.error { display: inline-block; color: #FF0000; } |
That’s it! You have a working AJAX login form in sidebar now which you have created without a plugin. It performs login and loads #divuser
with logged in user’s display name and link to AJAX logout.
Now we need to apply some functionality to show the same #divuser
and keeping the login form hidden on page refresh or redirect for logged in user. In part II of this article we covered that as AJAX logout.