The contact form is an essential element of every website, whether built using WordPress or any other CMS. The problem is that when you add a contact form plugin, it loads some default scripts and link tags on all website pages.
As we know the more scripts and files linking to our page, the more time it will take to load. Sometimes, these plugins are loading external CSS and JS files causing the web page to load even slower.
Table of Contents
So, How do we get rid of these slow-loading scripts and files?
In this tutorial, you will learn how to add a custom contact form without any plugins. We will cover these topics in this article:
What is a contact form?
A contact form is a simple form that usually gets input from the user (Name, Email, Phone, and Message) for the sake of communication. You can collect different details about a visitor who is interested in contacting you for some reason.
Most commonly, a contact form consists of three input fields: Name, Email, and Message. You can adjust the input fields according to the nature of the website accordingly.
Why do we use a contact form on our website?
There are several reasons for using a contact form on our website. From providing convenience to the visitor to the comfort of website admins, it serves a lot as:
Easy Communication
A contact form creates an easy and convenient communication channel between visitors of the website and the site admin. The visitor doesn’t have to find your email address and then compose a message to contact you. Instead, they can just fill up their details and the rest is handled by this form.
Spam Protection
If you are using a contact form on your WordPress website, it will prevent spammers from bursting messages in your inbox. Moreover, in this article, you will learn to add a custom contact form with a built-in math captcha.
Organized Information
Organizing contact details of visitors or clients can be an issue if you are dealing with them directly. By using a contact form, you can easily get organized information in your email inbox or you can create a separate page to display all contact form entries.
Security
Without a contact form, you will be exposing your business email to cyber and phishing attacks. You can prevent all these risks, by just adding a simple contact form with necessary input fields.
How to add a custom contact form on our WordPress website?
As we are not using any plugin to add this contact form, so you will have to be ready to modify some files in your theme. But don’t worry, I will get you through this with ease and matter of seconds. Just follow these steps with care and don’t forget to take a backup of your WordPress website in case of any problem.
Step 1: Adding HTML and JS to your Web Page
Create a new page and name it “Contact Us” or whatever you want to.
Click “Edit” and go to the page editor.
Click the Plus icon in the left corner and search for the HTML element.
Copy and Paste this HTML + JS Code into this HTML element.
<div id="form-message" style="color: green; font-weight: bold;"></div> <!-- Success/Error Message -->
<form id="contactForm">
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name" placeholder="Enter your Name" required>
</p>
<p>
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Enter your Email" required>
</p>
<p>
<label for="message">Message</label>
<textarea name="message" id="message" required placeholder="Type your message here..."></textarea>
</p>
<!-- CAPTCHA -->
<p>
<label id="captcha-label"></label> <!-- This will display the CAPTCHA equation -->
<input type="text" id="captcha" name="captcha" required placeholder="Enter the result">
</p>
<input type="hidden" id="captcha-result" name="captcha-result"> <!-- Hidden field to store the correct CAPTCHA answer -->
<p>
<input type="submit" id="submit" value="Send">
</p>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Generate a simple CAPTCHA with two random numbers
function generateCaptcha() {
var num1 = Math.floor(Math.random() * 10) + 1; // Random number between 1 and 10
var num2 = Math.floor(Math.random() * 10) + 1;
var sum = num1 + num2;
// Display the CAPTCHA equation
document.getElementById('captcha-label').textContent = `What is ${num1} + ${num2}?`;
// Store the correct answer in the hidden field
document.getElementById('captcha-result').value = sum;
}
// Generate CAPTCHA on page load
generateCaptcha();
// Handle form submission
document.getElementById('contactForm').addEventListener('submit', function(e) {
e.preventDefault(); // Prevent default form submission
var formData = new FormData(this); // Collect form data
// Validate CAPTCHA
var userCaptchaInput = formData.get('captcha');
var correctCaptcha = formData.get('captcha-result');
if (userCaptchaInput !== correctCaptcha) {
var messageDiv = document.getElementById('form-message');
messageDiv.textContent = 'CAPTCHA is incorrect. Please try again.';
messageDiv.style.color = 'red';
generateCaptcha(); // Generate a new CAPTCHA
return;
}
// AJAX request to submit the form to external PHP file
fetch('/contact-form.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
var messageDiv = document.getElementById('form-message');
if (data.success) {
// Display success message
messageDiv.textContent = data.data;
messageDiv.style.color = 'green';
document.getElementById('contactForm').reset(); // Reset form fields
generateCaptcha(); // Generate new CAPTCHA after submission
} else {
// Display error message
messageDiv.textContent = data.data;
messageDiv.style.color = 'red';
}
})
.catch(error => {
console.error('Error:', error);
});
});
});
</script>
The code marked in Orange color will be updated according to your file location. (Explained in the next step)
Step 2: Adding PHP Handler file to your WordPress theme
Once you have made changes to the Contact Us page, the next step is to handle the data sent by this form. We will use a simple mail function to send this data to your email address. For this step, you have to install a plugin to access theme files and create a new one.
(You can uninstall this plugin after we are done modifying the files)
- Install a new Plugin “File Manager“.
- Click on it after installing and activating it from the left sidebar.
- Go to “public_html“, and you will see all files of WordPress.
- Create a New file by clicking on the file icon in the top left corner of the file manager interface.
- Name the file as “contact-form.php“
- Copy and Paste this code into that PHP file.
- The file should have this path “public_html/contact-form.php“
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Sanitize and collect form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$captcha = filter_var($_POST['captcha'], FILTER_SANITIZE_STRING);
$captchaResult = filter_var($_POST['captcha-result'], FILTER_SANITIZE_STRING);
// Validate data
if (empty($name) || empty($email) || empty($message) || empty($captcha)) {
echo json_encode(array('success' => false, 'data' => 'All fields are required.'));
exit;
}
// Server-side CAPTCHA validation
if ($captcha !== $captchaResult) {
echo json_encode(array('success' => false, 'data' => 'Incorrect CAPTCHA.'));
exit;
}
// Email details
//ADD YOUR EMAILL HERE
$to = 'youremail@site.com';
$subject = $name.' Filled a Contact Form';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: " . $name . " <" . $email . ">\r\n"; // Sender's name and email
$body = "
<p><strong>Name:</strong> {$name}</p>
<p><strong>Email:</strong> {$email}</p>
<p><strong>Message:</strong><br>{$message}</p>
";
// Send email
if (mail($to, $subject, $body, $headers)) {
echo json_encode(array('success' => true, 'data' => 'Message sent successfully!'));
} else {
echo json_encode(array('success' => false, 'data' => 'Failed to send message.'));
}
}
?>
UPDATE YOUR EMAIL IN THE ABOVE CODE
Save this file and test by viewing the contact form in a browser window. By default, I have added a math captcha in this code to prevent spam entries.
Step 3: Testing your custom contact form with Gmail
After doing the above two steps, test your form thoroughly on different browsers to make sure it works fine. Sometimes, email is received in spam because of email reputation. To avoid this, configure SMTP on your website for secure and successful email delivery.
Conclusion and Results
By following these simple steps, you will have a simple contact form without any plugins in your WordPress website. You can update the code if you want to add or remove some fields with the help of a developer or chatGPT.