Ajax Login System with WordPress

In this tutorial, I’ll show you how to create a complete front-end login system with Ajax on WordPress. This tutorial can be done by creating a plugin but for this example, I’ll show only the files that you need to do this. If you put on your theme folder it’s work’s well.

The Form

For the HTML form, you need to use the method get in this example I only use username and password but you can put more fields as you want. I put to a P tag with class status to show messages during the login process. and for improving the security I used a wp_nonce_field to register a hidden field with ID


<form id="login" action="login" method="post">
  <input id="username" class="form-control" type="text" name="username" placeholder="User">
  <input id="password" class="form-control" type="password" name="password" placeholder="Senha">

  <p class="status"></p>
  
  <p> <a class="link" href="<?php echo wp_lostpassword_url(); ?>">Forgot Password?</a>. </p>

  <input class="btn-login btn btn-success text-uppercase" type="submit" value="Login" name="submit">

 <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>

</form>

Now we need a little bit of JavaScript to show dialog box and perform Ajax Login form on submit, for this I’ll create a file call ajax-login.js:


jQuery(document).ready(function($) {
  // Show the login dialog box on click
  $('a#show_login').on('click', function(e) {
    $('body').prepend('');
    $('form#login').fadeIn(500);
    $('div.login_overlay, form#login a.close').on('click', function() {
      $('div.login_overlay').remove();
      $('form#login').hide();
    });
    e.preventDefault();
  });

  // Perform AJAX login on form submit
  $('form#login').on('submit', function(e) {
    $('form#login p.status')
      .show()
      .text(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').text(data.message);
        if (data.loggedin == true) {
          document.location.href = ajax_login_object.redirecturl;
        }
      }
    });
    e.preventDefault();
  });
https://marioernestoms.com/wp-admin/media-upload.php?post_id=459&type=image&TB_iframe=1&width=753&height=812
});

Now for start Ajax Login we need create a simple function to init, Let’s see how to do this:


/**
 * ------------------------------
 * Function to start ajax login.
 * ------------------------------
 */
function ajax_login_init() {

	wp_register_script( 'ajax-login-script', get_stylesheet_directory_uri() . 'ajax-login.js', array( 'jquery' ) );
	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(), // Here you can change this if you want to open another page.
		'loadingmessage' => __( 'Enviando as informações, aguarde ...' ),
	));

	// 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' );
}

And for a finish I’ll create a function to send Ajax Login and process the login form, you can put this code on functions.php file but is recommend create a plugin with all files show here in this tutorial:


/**
 * ------------------------------
 * Function to send 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'] = filter_input( INPUT_POST, 'username' );
	$info['user_password'] = filter_input( INPUT_POST, 'password' );
	$info['remember'] = true;

	$user_signon = wp_signon( $info, false );
	if ( is_wp_error( $user_signon ) ) {
		echo wp_json_encode( array(
			'loggedin'	=> false,
			'message'	=> __( 'User or password wrong.' ), // Customize this text with whatever message you want.
		));
	} else {
		echo wp_json_encode( array(
			'loggedin'	=> true,
			'message'	=> __( 'Success logged-in, redirect ...' ), // Customize this text with whatever message you want.
			)
		);
	}

	die();
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.