Tuesday, June 2, 2020

WordPress Custom Login Form via Ajax

Create & implement custom login form via Ajax to give user login feature. Here I have developed for this a shortcode so easily put this code in any files (in theme functions.php, plugin's file) and can placed shortcode in any template file, sidebar file, page content, post content, widget.

Here I have used only 'wp_ajax_nopriv_' action hook to accept ajax request because 'wp_ajax_nopriv_' action hook is accept only requests are send via frontend pages (non-logged in users).

# Create a shortcode [login_form] so we can put it wherever we want
# and this put functions.php or your desire plugin

add_shortcode('login_form', 'pkt_login_form');
function pkt_login_form($attr) {
	/* define desire key index */
    $attr = shortcode_atts( array(
		
	), $attr );

    extract($attr);

    ob_start();
    require 'login.php';
    $return = ob_get_clean();
	return $return;
}


# here login.php page code 
<form action="" id="login_form" method="POST">
    <input name="pkt_login" type="hidden" value="1" />
        

    <div class="form-check">
        <label>Email Address</label>
        <input name="email" placeholder="Your registered email address" required="" type="email" />
    </div>

    <div class="form-check">
        <label>Password</label>
        <input name="password" required="" type="password" />
    </div>

    <div class="form-check">
        <input class="form-check-input" name="remember" type="checkbox" value="1" />
        <label>Keep me logged in</label>
        <a href="&lt;?php echo home_url('wp-login.php?action=lostpassword') ?&gt;" id="forget_pass_btn">Forget Password?</a>
    </div>
    <div class="btn_mainstyle">
        <button class="btn_style btn_submit" type="submit">Log in</button>
        &nbsp;
        <span class="spinner-border text-primary" style="display: none; height: 20px; width: 20px;"></span>
    </div>
</form>


<script>
	jQuery('#login_form').submit(function (e) {
		e.preventDefault();
		let th = jQuery(this);
		let data = th.serialize();
		th.find('.btn_mainstyle span').show()
		jQuery('.response-msg').text('').hide()
		jQuery('.btn_submit').attr('disabled', true)

		jQuery.ajax({
			url: '<?php echo admin_url('admin-ajax.php') ?>',
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'pkt_login',
				data: data
			},
			success: function (res) {
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html(res.msg).show();

				if (res.status) {
					jQuery('.response-msg').removeClass('text-danger').addClass('text-success');
					setTimeout(() => {
						window.location.href = res.redirectTo;
					}, 1500);
				} else {
					jQuery('.response-msg').removeClass('text-success').addClass('text-danger');
					jQuery('.btn_submit').attr('disabled', false)
				}

			},
			error: function (x, h) {
				console.log(x, h);
				th.find('.btn_mainstyle span').hide();
				jQuery('.response-msg').html('An error has occured during Login')
					.show().addClass('text-danger');
				jQuery('.btn_submit').attr('disabled', false)
			}
		});
		return false;
	});
</script>



# now add a ajax handler to receive ajax request
# here need to use only 'wp_ajax_nopriv_' action 

add_action('wp_ajax_nopriv_pkt_login', 'pkt_login');
function pkt_login() {
	$response = ['status' =&gt; false];
	if (empty($_POST['data']))
		$response['msg'] = 'Please flll out the form!!';
	else {
		parse_str($_POST['data'], $data);
		if (! wp_verify_nonce( $data['pkt_form_nonce'], 'pkt_nonce' )) {
			$response['msg'] = 'Our Site is protected!!';

		} else {
			$user_email = sanitize_email($data['email']);
			$password = $data['password'];

			if (! is_email( $user_email ) ) {
				$response['msg'] = 'Error: The email address isn&#8217;t correct. or already registered.';

			} elseif (!email_exists( $user_email )) {
				$response['msg'] = 'Error: The email address is not registered.';

			} else {
				$creds = array(
					'user_login'    =&gt; $user_email,
					'user_password' =&gt; $password,
					'remember'      =&gt; empty($data['remember']) ? false : true
				);

				$user = wp_signon( $creds, true );
				if ( is_wp_error( $user ) ) {
					$response['msg'] = $user-&gt;get_error_message();
				} else {
					$response['status'] = true;
					$response['redirectTo'] = site_url();
					$response['msg'] = 'Login successfully.';
				}
			}
		}
	}
	echo json_encode($response);
	wp_die();
}

No comments:

Post a Comment