Creating a custom email OTP (One-Time Password) system in a WordPress contact form

Creating a custom email OTP (One-Time Password) system in a WordPress contact form involves these steps:

Steps to Implement Email OTP in WordPress Contact Form

  1. Create a Custom Contact Form
    • You can create a custom contact form using a plugin like Contact Form 7, WPForms, or create one manually using custom code.
  2. Send OTP to User’s Email
    • When a user fills out the form and submits, generate a random OTP and send it to the email provided.
  3. Store the OTP Temporarily
    • Save the OTP in a session or database with a timestamp to allow verification within a specific time.
  4. Verify the OTP
    • Provide a second step in the form where the user can enter the OTP for verification.
  5. Proceed After Verification
    • If the OTP matches and is within the valid time, allow the user to proceed with the contact form submission.

Code Example for Custom Implementation

Here is an example of how to do this using custom code in a WordPress theme or plugin:

Step 1: Enqueue Scripts

Add the following in your theme’s functions.php file to load necessary scripts:

function custom_enqueue_scripts() {
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'custom_enqueue_scripts');

Step 2: Create the Form

Add the following form to a page or template:

<form id="custom-contact-form" method="post" action="">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <button type="button" id="send-otp">Send OTP</button>

    <div id="otp-section" style="display:none;">
        <label for="otp">Enter OTP:</label>
        <input type="text" id="otp" name="otp" required>
        <button type="submit" id="verify-otp">Submit</button>
    </div>
</form>
<div id="response-message"></div>

Step 3: Handle OTP via AJAX

Add this PHP code to handle OTP generation and verification:

add_action('wp_ajax_send_otp', 'handle_send_otp');
add_action('wp_ajax_nopriv_send_otp', 'handle_send_otp');

function handle_send_otp() {
    session_start();
    $email = sanitize_email($_POST['email']);
    $otp = rand(100000, 999999); // Generate a 6-digit OTP
    $_SESSION['otp'] = $otp;
    $_SESSION['otp_expiry'] = time() + 300; // OTP valid for 5 minutes

    // Send the OTP via email
    $subject = "Your OTP Code";
    $message = "Your OTP is: $otp";
    $headers = ['Content-Type: text/html; charset=UTF-8'];
    wp_mail($email, $subject, $message, $headers);

    wp_send_json_success('OTP sent successfully!');
}

add_action('wp_ajax_verify_otp', 'handle_verify_otp');
add_action('wp_ajax_nopriv_verify_otp', 'handle_verify_otp');

function handle_verify_otp() {
    session_start();
    $user_otp = sanitize_text_field($_POST['otp']);

    if (isset($_SESSION['otp']) && isset($_SESSION['otp_expiry'])) {
        if (time() > $_SESSION['otp_expiry']) {
            wp_send_json_error('OTP expired!');
        } elseif ($user_otp == $_SESSION['otp']) {
            unset($_SESSION['otp']);
            unset($_SESSION['otp_expiry']);
            wp_send_json_success('OTP verified!');
        } else {
            wp_send_json_error('Invalid OTP!');
        }
    } else {
        wp_send_json_error('No OTP found!');
    }
}

Step 4: Add AJAX in JavaScript

Create a custom JavaScript file, enqueue it, and add the following:

jQuery(document).ready(function ($) {
    $('#send-otp').click(function () {
        const email = $('#email').val();

        if (email) {
            $.ajax({
                url: ajaxurl, // WordPress AJAX URL
                method: 'POST',
                data: {
                    action: 'send_otp',
                    email: email,
                },
                success: function (response) {
                    if (response.success) {
                        alert(response.data);
                        $('#otp-section').show();
                    } else {
                        alert('Failed to send OTP. Please try again.');
                    }
                },
            });
        } else {
            alert('Please enter your email.');
        }
    });

    $('#custom-contact-form').submit(function (e) {
        e.preventDefault();
        const otp = $('#otp').val();

        $.ajax({
            url: ajaxurl,
            method: 'POST',
            data: {
                action: 'verify_otp',
                otp: otp,
            },
            success: function (response) {
                if (response.success) {
                    $('#response-message').text('Form submitted successfully!');
                } else {
                    $('#response-message').text(response.data);
                }
            },
        });
    });
});

Step 5: Test the Form

  • Add the form to a WordPress page.
  • Test sending and verifying the OTP.

Notes

  • For session handling, ensure your hosting supports PHP sessions.
  • You can enhance security by storing the OTP in a database instead of PHP sessions.
  • Consider using reCAPTCHA or another spam protection mechanism.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x