Saturday, June 13, 2020

Set Media Attribute In All Styles to Improve Your Website's Page Speed with One Simple JavaScript Code

Are you looking for ways to improve your website's page speed and performance? Look no further than this simple JavaScript code that can make a big impact on your site's speed.

<script>
    // Set media attribute to "all" for all stylesheets
    const stylesheets = document.querySelectorAll('link[rel="stylesheet"]');
    stylesheets.forEach(stylesheet => {
        stylesheet.media = 'all';
    });
</script>

The code sets the media 
attribute of all stylesheets to "all", which can improve page speed on Google PageSpeed Insights. By doing this, the browser can load all stylesheets at once, instead of waiting for them to load one by one. This can significantly reduce the time it takes for your website to load, which can improve user experience and search engine rankings.
 
To implement this code, simply add it to the end of your page, right before the closing body tag. The code uses modern JavaScript syntax, making it more efficient and easier to read than older JavaScript code.

By improving your website's page speed, you can engage visitors and keep them on your site longer. Slow-loading websites can lead to high bounce rates and lost revenue. With this simple JavaScript code, you can improve your website's performance and provide a better user experience for your visitors.

Try implementing this code on your website today and see the difference it can make in your page speed and overall performance.

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