If you want to implement Wordpress Frontend Ajax Login in your project or blog, Please refer following tutorial I had implemented in my blog.
Following Script will does this.
The above script will localize the ajax URL and nonce data using wp_localize_script() function.
Here is that login function.
For detailed reference refer following tutorial.
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:
$(document).on('click','#login_btn',function(){ jQuery.post( ajax_obj.ajax_url, { 'action': 'login', 'data': 'foobarid', 'username' : $('#login_username').val(), 'password' : $('#password').val(), nonce : ajax_obj.smart_nonce }, function(response){ data = jQuery.parseJSON(response); if( data.flag == true ){ location.reload(); }else{ $('#login_btn').button('reset'); $('#login_fail').show(); } } ); });
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(); }else{ $data['flag'] = true; $data['msg'] = "Login Successful. Please wait..."; } echo json_encode($data); die(); }
For detailed reference refer following tutorial.
Light Weight WordPress Frontend Ajax User Login and Registration
0 comments:
Post a Comment