WordPress offers a flexible platform for website development, including user authentication and login systems. In this tutorial, we’ll create a custom login form integrated with AJAX, allowing for smoother user experiences and dynamic feedback.

Step 1: Enqueue SweetAlert Library

SweetAlert is a customizable JavaScript library for creating beautiful alerts. First, include the SweetAlert library in your WordPress theme. You can do this by adding the following code to your theme’s functions.php file:

function enqueue_sweetalert2() {
    // Enqueue SweetAlert2 CSS
    wp_enqueue_style('sweetalert2-css', 'https://cdn.jsdelivr.net/npm/sweetalert2@10');
    // Enqueue SweetAlert2 JS and set jQuery as a dependency
    wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2@10', array('jquery'), '', true);
}
add_action('wp_enqueue_scripts', 'enqueue_sweetalert2');

Step 2: Implement Custom Login Form

Add this snippet to trigger and displaying form login

function custom_script() { ?>
    <script>
        jQuery(document).ready(function ($) {
            $('.login-button').click(function () {
                Swal.fire({
                    title: 'Login',
                    html: `
                        <form id="login-form" class="form form--1">
                            <div class="form__group">
                                <label for="username" class="form__label">Username:</label>
                                <input type="text" name="log" id="username" class="form__input" required>
                            </div>
                            <div class="form__group">
                                <label for="password" class="form__label">Password:</label>
                                <input type="password" name="pwd" id="password" class="form__input" required>
                            </div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Login',
                    cancelButtonText: 'Cancel',
                    showLoaderOnConfirm: true,
                    buttonsStyling: false,
                    customClass: {
                        confirmButton: 'brxe-button login-button bricks-button sm bricks-background-primary',
                        cancelButton: 'brxe-button login-button bricks-button sm bricks-background-warning',
                        actions: 'gap-2xs',
                    },
                    preConfirm: function () {
                        // Your login logic goes here
                        return new Promise(function (resolve, reject) {
                            // Perform AJAX login
                            const username = $('#username').val();
                            const password = $('#password').val();
                            $.ajax({
                                type: 'POST',
                                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                                data: {
                                    action: 'custom_login',
                                    username: username,
                                    password: password,
                                },
                                success: function (response) {
                                    if (response === 'success') {
                                        // If login is successful, resolve the promise
                                        resolve();
                                    } else {
                                        // If login fails, show SweetAlert error message
                                        Swal.fire({
                                            icon: 'error',
                                            title: 'Oops...',
                                            text: 'Something went wrong!',
                                            footer: '<a href="#">Why do I have this issue?</a>'
                                        });
                                    }
                                },
                            });
                        });
                    },
                }).then(function (result) {
                    if (result.isConfirmed) {
                        // Show success message and button to close dialog and go to /account
                        Swal.fire({
                            icon: 'success',
                            title: 'Your successful login',
                            showConfirmButton: false,
                            html: `
                                <button id="go-to-account" class="brxe-button header__button login-button bricks-button sm bricks-background-primary">Go to Account</button>
                            `,
                        });
                        // Handle button click event to redirect to /account
                        $('#go-to-account').click(function () {
                            window.location.href = '/account';
                        });
                    }
                });
            });
        });
    </script>
<?php } 
add_action('wp_footer', 'custom_script');

Step 3: Handle AJAX Login

Add the following PHP functions to your functions.php file to handle the AJAX login process. These functions sanitize the login credentials and attempt to sign in the user using WordPress’s wp_signon() function. They return a success or error message based on the login attempt.

function custom_login() {
    $username = sanitize_user($_POST['username']);
    $password = $_POST['password'];

    $creds = array(
        'user_login' => $username,
        'user_password' => $password,
        'remember' => true,
    );

    $user = wp_signon($creds, false);

    if (is_wp_error($user)) {
        echo 'error';
    } else {
        echo 'success';
    }

    wp_die();
}

add_action('wp_ajax_custom_login', 'custom_login');
add_action('wp_ajax_nopriv_custom_login', 'custom_login');

Step 4: Display the Login Button

Finally, add the following  code wherever you want to display the login button on your WordPress site:

<button class="login-button">Login</button>
Watch video tutorial here