To enable Ajax-based login in your WordPress website, follow the steps below for a seamless, reload-free login experience:
1. Edit Your Theme’s Functions.php
In your WordPress admin panel, navigate to Appearance > Theme Editor, and open functions.php
from your active theme. Add this:
// Load jQuery and custom script function enqueue_custom_scripts() { wp_enqueue_script('jquery'); wp_enqueue_script('custom-scripts', get_stylesheet_directory_uri() . '/js/custom-scripts.js', array('jquery'), '1.0', true); wp_localize_script('custom-scripts', 'ajax_login_object', array( 'ajax_url' => admin_url('admin-ajax.php'), 'redirect_url' => home_url() )); } add_action('wp_enqueue_scripts', 'enqueue_custom_scripts'); // Ajax login function function ajax_login() { check_ajax_referer('ajax-login-nonce', 'security'); $info = array( 'user_login' => $_POST['username'], 'user_password' => $_POST['password'], 'remember' => true ); $user_signin = wp_signon($info, false); if (is_wp_error($user_signin)) { echo json_encode(array('loggedin' => false, 'message' => __('Invalid credentials.', 'text-domain'))); } else { echo json_encode(array('loggedin' => true, 'message' => __('Login successful.', 'text-domain'))); } wp_die(); } add_action('wp_ajax_ajax_login', 'ajax_login'); add_action('wp_ajax_nopriv_ajax_login', 'ajax_login');
2. Add JavaScript
Create /js/custom-scripts.js
in your theme folder. Then, insert the following code:
jQuery(document).ready(function($) { $('#login-form').on('submit', function(e) { e.preventDefault(); var form = $(this), submitBtn = form.find('input[type="submit"]'), messageBox = form.find('.login-message'), username = form.find('#username').val(), password = form.find('#password').val(); submitBtn.prop('disabled', true); $.ajax({ type: 'POST', url: ajax_login_object.ajax_url, data: { action: 'ajax_login', username: username, password: password, security: $('#ajax-login-nonce').val() }, success: function(response) { var data = JSON.parse(response); messageBox.html('<p class="' + (data.loggedin ? 'login-success' : 'login-error') + '">' + data.message + '</p>'); if (data.loggedin) { window.location.href = ajax_login_object.redirect_url; } submitBtn.prop('disabled', false); }, error: function() { messageBox.html('<p class="login-error">An error occurred.</p>'); submitBtn.prop('disabled', false); } }); }); });
3. Create the Login Form
Place this form where you want it to appear:
<form id="login-form" action="" method="post"> <input type="text" id="username" name="username" placeholder="Username" required> <input type="password" id="password" name="password" placeholder="Password" required> <?php wp_nonce_field('ajax-login-nonce', 'ajax-login-nonce'); ?> <input type="submit" value="Log In"> <div class="login-message"></div> </form>
Note: Use a child theme or plugin to prevent changes from being overwritten during theme updates. Always back up your site before editing core files.