Wordpress Frontend Ajax Login

Leave a Comment
If you want to implement Wordpress Frontend Ajax Login in your project or blog, Please refer following tutorial I had implemented in my blog.

Light Weight WordPress Frontend Ajax User Login and Registration

Step 1: Initialize Wordpress Ajax Call:

We need define ajax url before we are going to make Ajax request using jQuery.

Following Script will does this.

wp_register_script( 'ajax', get_template_directory_uri() . '/library/js/ajax.js', array('jquery'), '1.2' );
wp_enqueue_script( 'ajax' );
wp_localize_script( 'ajax', 'ajax_obj', 
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'smart_nonce' => wp_create_nonce( 'myajax-nonce' )  ) );

The above script will localize the ajax URL and nonce data using wp_localize_script() function.

Step 2: Make  Wordpress AjaxUsing jQuery:

         'action': 'login',
         'data':   'foobarid',
         'username' : $('#login_username').val(),
         'password' : $('#password').val(),
          nonce : ajax_obj.smart_nonce
         data = jQuery.parseJSON(response);
         if( data.flag == true ){

Step 2: PHP Script Wordpress Ajax Reqest:

We need register action to handle Ajax request coming from client side. Here is the script to register Wordpress action hook.
add_action('wp_ajax_login',        'login');
add_action('wp_ajax_nopriv_login', 'login');

Here is that login function.
function login() {
 $nonce = $_POST['nonce'];
 if ( ! wp_verify_nonce( $nonce, 'myajax-nonce' ) )
 die ( 'Invalid Request!');

 $creds = array();
 $data = array();
 $creds['user_login'] = $_POST['username'];
 $creds['user_password'] = $_POST['password'];
 $creds['remember'] = false;
 $user = wp_signon( $creds, false );
 if ( is_wp_error($user) ){
  $data['flag'] = false;
  $data['msg'] = $user->get_error_message();
  $data['flag'] = true;
  $data['msg'] = "Login Successful. Please wait...";
 echo json_encode($data);

For detailed reference refer following tutorial.
Light Weight WordPress Frontend Ajax User Login and Registration


Post a Comment