WordPress Ajax login

To implement Ajax login in WordPress, you can follow these steps:

1. Open the theme’s functions.php file in your WordPress theme directory.
2. Add the following code to the file:

 

// Enqueue jQuery and custom JavaScript
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 ajax_login() {
    check_ajax_referer('ajax-login-nonce', 'security');
    
    $info = array();
    $info['user_login'] = $_POST['username'];
    $info['user_password'] = $_POST['password'];
    $info['remember'] = true;
    
    $user_signin = wp_signon($info, false);
    if (is_wp_error($user_signin)) {
        echo json_encode(array('loggedin' => false, 'message' => __('Wrong username or password.', 'text-domain')));
    } else {
        echo json_encode(array('loggedin' => true, 'message' => __('Login successful!', 'text-domain')));
    }
    die();
}
add_action('wp_ajax_ajax_login', 'ajax_login');
add_action('wp_ajax_nopriv_ajax_login', 'ajax_login');

 

3. Create a new directory in your theme called “js” (if it doesn’t exist already) and create a new file called “custom-scripts.js” inside that directory.
4. Open the “custom-scripts.js” file and add the following code:

 

jQuery(document).ready(function($) {
    // Ajax login form submission
    $(document).on('submit', '#login-form', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var submitButton = form.find('input[type="submit"]');
        var loginMessage = form.find('.login-message');
        var usernameField = form.find('#username');
        var passwordField = form.find('#password');
        
        submitButton.attr('disabled', 'disabled');
        
        $.ajax({
            type: 'POST',
            url: ajax_login_object.ajax_url,
            data: {
                action: 'ajax_login',
                username: usernameField.val(),
                password: passwordField.val(),
                security: $('input#ajax-login-nonce').val()
            },
            success: function(data) {
                var response = JSON.parse(data);
                
                if (response.loggedin === true) {
                    loginMessage.html('<p class="login-success">' + response.message + '</p>');
                    window.location.href = ajax_login_object.redirect_url;
                } else {
                    loginMessage.html('<p class="login-error">' + response.message + '</p>');
                }
                
                submitButton.removeAttr('disabled');
            },
            error: function() {
                loginMessage.html('<p class="login-error">' + ajax_login_object.error_message + '</p>');
                submitButton.removeAttr('disabled');
            }
        });
    });
});

 

5. Save the changes and upload the modified functions.php and custom-scripts.js files back to your server.

This code enqueues the necessary scripts, including jQuery and custom JavaScript. It sets up the Ajax login functionality, handling the form submission, validating the user credentials, and logging in the user. The login response is returned as JSON and displayed on the login form accordingly.

To create the login form in your WordPress theme, you can use the following HTML markup:

<form id="login-form" action="" method="post">
    <input type="text" name="username" id="username" placeholder="Username" required>
    <input type="password" name="password" id="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>

Make sure to place this form where you want the login form to appear on your website.

Please note that you may need to adjust the file paths and customize the form styling and error/success messages to fit your specific needs.

Related Blogs

Delete Product Image With Product Delete In WooCommerce

In WooCommerce, when you delete a product, by default, the product images are not automatically deleted from the server to avoid accidental data loss. However, you can add a custom action to delete the product images when a product is deleted. Here’s a step-by-step guide to achieve this:

How to log information, warnings, errors In wordpress

To create a custom write_log() function for WordPress, you can use the error_log() function to write messages to the error log. This function will allow you to log information, warnings, errors, or any other messages during development or debugging.

Ultimate Guide to Custom Meta Boxes in WordPress

In WordPress, `add_meta_boxes` is an action hook that allows developers to add custom meta boxes to different post types’ edit screens. Meta boxes are additional sections on the post editor screen where you can add and display custom fields or other types of data related to the post.

Request A Quote

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.