In this tutorial we’re going to learn how to build an AJAX login form for a WordPress site. I’m going to show you how to put this in your theme, but if you have a commercial theme I recommend putting this functionality into a plugin to make updates easier. So without further ado, let’s get started!
1. Add The Form To Your Theme
The first thing we need is a form for our users to type their login details into. I don’t want it to be the first thing loaded on the page, so to keep markup nice and clean, I’m adding the following code to my theme’s footer.php before the wp_footer()
function. It should work equally well in other template files so put it where you’d like it.
<form id="ajaxlogin" action="login" method="post"><h3 class="h1"><!?php _e('Login To', 'blueleaf') ?></h3> <label for="username"><?php _e('Email', 'blueleaf'); ?></label> <input id="username" name="username" type="text" > <label for="password"><?php _e('Password', 'blueleaf'); ?></label> <input id="password" name="password" type="password" > <button name="submit" type="submit" value="<?php _e('Login', 'blueleaf') ?>"><?php _e('Login', 'blueleaf') ?></button> <a class="register small" href="<?php bloginfo('url'); ?>/register/"><?php _e('Register...', 'blueleaf'); ?></a><br> <a class="lost small" href="<?php echo wp_lostpassword_url(); ?>"><?php _e('Lost your password?' , 'blueleaf'); ?></a> <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?> </form>
Pretty basic HTML5 there. Our form element, which contains a title, our username and password fields and a submit button. There is an empty paragraph element which will display the status of our AJAX request. At the bottom of the form we have a link for registration and a link for resetting a password. Take note of the wp_nonce_field()
. This is one of WordPress’ built in security functions. See the WordPress codex if you want to know more.
2. JavaScript
Next we need the JavaScript which will send the request front the form and receive the result from the server. In your theme (or plugin) folder make a folder called js and in there create a file called ajax-login-script.js. Paste the following into the file:
jQuery(document).ready(function($) { // Perform AJAX login on form submit $('form#login').on('submit', function(e){ $('form#login p.status').show().html(ajax_login_object.loadingmessage); $.ajax({ type: 'POST', dataType: 'json', url: ajax_login_object.ajaxurl, data: { 'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin 'username': $('form#login #username').val(), 'password': $('form#login #password').val(), 'security': $('form#login #security').val() }, success: function(data){ $('form#login p.status').html(data.message); if (data.loggedin == true){ document.location.href = ajax_login_object.redirecturl; } } }); e.preventDefault(); }); });
3. Load the script with WordPress
Now we have our JavaScript file we need to load it into WordPress then localise the script to work with WordPress’ AJAX. For this we’ll need to add some code to your functions.php.
//AJAX Login scripts add_action( 'wp_enqueue_scripts', 'load_ajax_login_script', 999 ); function load_ajax_login_script() { wp_register_script('ajax-login-script', get_template_directory_uri() . '/js/ajax-login-script.js', array('jquery') ); wp_enqueue_script( 'jquery' ); wp_enqueue_script('ajax-login-script'); wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'redirecturl' => $_SERVER['REQUEST_URI'], 'loadingmessage' => __('Signing in, please wait...') )); }
Here we register our script in the load-ajax-login-script
function which is called with the WordPress hook wp_enqueue_scripts
. We will also need jQuery, which is included with WordPress, so next we enqueue both jQuery and our login script which loads them when you view a page on your site. Finally, we use wp_localize_script()
and set a few parameters for our login script. Here I have set the redirect url to the same page that is being viewed but you could set it to whatever page you want your user to see when they log in. On my website I went one step further and have a different redirect if a blog page is not being viewed using this:
// check if it's a blog page global $post; $posttype = get_post_type($post); if ($posttype == 'post') { $loginredirect = $_SERVER['REQUEST_URI']; } else { $loginredirect = '/services/clientarea'; } wp_localize_script( 'ajax-login-script', 'ajax_login_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'redirecturl' => $loginredirect, 'loadingmessage' => __('Signing in, please wait...') ));
4. Add the Log on function
This is the last step. We need to add a function that validates the user and logs them on if their credentials are correct. Also in functions.php we are going to add:
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' ); 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 { echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...'))); } die(); }
Conclusion
That about wraps it up. You should now have a working ajax login form on your site, although it may look a bit shabby! You can move the form where you’d like it on the page using css and have a go at styling it. Next week I’ll cover how to turn it into a nicely styled pop-up.