Skip to content (Press Enter)

marioernestoms

WordPress Specialist

  • About

Ajax Login System with WordPress

by marioernestomsupdated on 8 de January de 202030 de April de 2019

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


<?php if ( ! is_user_logged_in() ) : ?>
<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>
<?php else : ?>

   
   <?php
   if ( ( $current_user instanceof WP_User ) ) {

      echo get_avatar( $current_user->ID, 32 );
    }
    ?>
    
    
<?php echo '

' . $current_user->user_firstname . ' ' . $current_user->user_lastname . '

'; ?>
<?php endif; ?>

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(); }); });

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();
}

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

HTML/CSS/JS WordPress
0

marioernestoms

Post Navigation

Previous Article
Next Article

Recent Posts

  • WooCommerce – Block add to cart button
  • WooCommerce – Remove add to cart button
  • Ajax Login System with WordPress
  • How to install WordPress on VPS with SSH
  • Troubleshoot WordPress update failure message

Categories

  • HTML/CSS/JS
  • Servidores
  • WordPress
Recommended for you...

WooCommerce – Block add to cart button

by marioernestoms
Recommended for you...

Learn to use Ajax in WordPress

by marioernestoms
Recommended for you...

WooCommerce – Remove add to cart button

by marioernestoms

Leave a Reply Cancel 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.

© Copyright 2021 marioernestoms. All Rights Reserved. The Ultralight | Developed By Rara Theme. Powered by WordPress.