Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Create a Contact Form in WordPress

#1
How to Create a Contact Form in WordPress

Last modified on March 31st, 2021.

A contact form is an important component of any website. It acts as a bridge between the provider and customer. Creating a contact form for a WordPress platform is an easy job. You need to go through just a few steps to follow to launch a successful contact form for a WordPress site.

We have seen too many varieties of contact forms example in core PHP. No matter the platform, framework or CMS, but the concept is the same to write the process flow.

So, if you are familiar with a contact form about how it is working, then it is easy to understand the WordPress version of it.

If you are looking for a full-fledged secure, spam free contact form, then get Iris.

Wordpress Contact Formhttps://phppot.com/wp-content/uploads/20...00x288.png 300w, https://phppot.com/wp-content/uploads/20...50x528.png 550w, https://phppot.com/wp-content/uploads/20...68x738.png 768w" sizes="(max-width: 1011px) 100vw, 1011px">

What is inside?


  1. Create WordPress environment
  2. Create a new contact page using WordPress admin
  3. Create child-theme for the active theme
  4. How to create contact template
  5. Send AJAX request using wp_ajax hooks
  6. WordPress contact form output

Create WordPress environment


Set up the WordPress environment to create a contact form in that. The prerequisites of setting up WordPress are,

  • PHP 7.4 and above.
  • MySQL 5.6 and above or MariaDB 10.1 and above.
  • Apache or Ngink (mod_rewrite enabled)
  • Https support.

In a previous article, we have seen how to install WordPress. The linked article has the steps to simply install WordPress into your server.

Create a new contact page using WordPress admin


After installation, it will allow login to the WordPress admin panel.

In the left menu Pages->Add New navigates to create a new contact page. It will ask for the page title and content into it.

There are various ways to display the contact page content.

  1. The contact HTML can be directly added into the create-new-page and admin interface.
  2. Showing contact layout with the WordPress template-files.
  3. Registering shortcodes to render contact page layout in the frontend.

In this example code, I used the WordPress template files to load the contact layout.

Create child-theme for the active theme


I have created the WordPress child theme to customize the currently activated theme.

The below screenshot shows the theme’s file structure with the child theme. The child theme has the WordPress template file contact-template.php. This file has the contact HTML with the client-side AJAX script.

The functions.php file hooks the wp_ajax to process the contact form on submit.

Contact Form WordPress Fileshttps://phppot.com/wp-content/uploads/20...00x106.png 300w" sizes="(max-width: 315px) 100vw, 315px">

This is the WordPress template file create for this contact form example.

It loads page title and content created in the admin panel to display on the contact page.

Added to that, it has the contact form HTML. The form contains the basic fields name, email and more. All the fields are mandatory and validated via JavaScript.

contact-template.php

<?php
/* Template Name: Contact Template */
get_header(); /* Start the Loop */
while (have_posts()) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header alignwide"> <?php the_title('<h1 class="entry-title">', '</h1>'); ?> </header> <!-- .entry-header --> <div class="entry-content"> <?php the_content('<p>', '</p>'); ?> <link rel="stylesheet" type="text/css" href="/wordpress/wp-content/themes/twentytwentyone-child/style.css"> <form name="contactForm" id="contactForm" method="post" on‌submit="return formValidation()" action=""> <div class="row"> <div class="label">Name:</div> <input type="text" id="name" name="name"> </div> <div class="row"> <div class="label">Email:</div> <input type="text" id="email" name="email"> </div> <div class="row"> <div class="label">Subject:</div> <input type="text" id="subject" name="subject"> </div> <div class="row"> <div class="label">Message:</div> <textarea id="message" name="message" rows="5"></textarea> </div> <div class="row"> <input type="submit" value="Submit"> <span id="status"></span> </div> </form> </div>
</article>
<!-- #post-<?php the_ID(); ?> -->
<?php
endwhile
; // End of the loop. get_footer();
?>

As specified the name of the template at the beginning of the file, the Template dropdown lists in the admin.

Choose the QUICK EDIT option of the contact page from Pages->All Pages. The below screenshot displays the option to choose the contact template for the page.

Choose Custom Template in WordPresshttps://phppot.com/wp-content/uploads/20...300x87.png 300w, https://phppot.com/wp-content/uploads/20...50x160.png 550w, https://phppot.com/wp-content/uploads/20...68x223.png 768w" sizes="(max-width: 816px) 100vw, 816px">

Send AJAX request using wp_ajax hooks


This JavaScript code has two functions. The formValidation() is for validating the contact form and the processContactSubmit() is to call wp_ajax to process the contact form in WordPress.

The AJAX request passes the validated form data to the server-side. It calls the admin_ajax.php with the action parameter to hook the wp_ajax.

AJAX script

<script>
function formValidation() { event.preventDefault(); var name = document.forms["contactForm"]["name"].value; var email = document.forms["contactForm"]["email"].value; var subject = document.forms["contactForm"]["subject"].value; var message = document.forms["contactForm"]["message"].value; document.getElementById('status').innerHTML = ''; var errorMessage="<span class='error'>All fields are required.</span>"; var regEx = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if (name.trim() == "" ||email.trim() == "" || subject.trim() == "" || message.trim() == "") { document.getElementById('status').innerHTML = errorMessage; return false; } if (!regEx.test(email)) { var errorMessage="<span class='error'>Invalid email.</span>"; document.getElementById('status').innerHTML = errorMessage; return false; } processContactSubmit(); return true; } function processContactSubmit() { var request = new XMLHttpRequest(); request.open("POST", "/wordpress/wp-admin/admin-ajax.php?action=process_contact_form"); request.onreadystatechange = function() { if(this.readyState === 4 && this.status === 200) { document.getElementById("status").innerHTML = this.responseText; } }; var myForm = document.getElementById("contactForm"); var formData = new FormData(contactForm); request.send(formData);
}
</script>

functions.php

In functions.php, it hooks the wp_ajax action process_contact_form() on requesting via AJAX.

It receives the form data to set the contact email subject and the main body content.

It also sets the mail header and recipient email address to pass through the mail sending function.

This code uses the wp_mail to send the contact email using WordPress. There are WordPress plugins to enable SMTP for sending emails.

<?php
add_action('wp_ajax_nopriv_process_contact_form', 'process_contact_form'); function process_contact_form()
{ $to = "Recipient Email Address"; $subject = $_POST["subject"]; $headers = "Testing"; $message = $_POST["message"]; $attachments = ""; $sent = wp_mail($to, $subject, $message, $headers, $attachments); if (! $sent) { echo "<span class='error'>Problem in sending mail.</span>"; } else { echo "<span class='success'>Hi, thank you for the message.</span>"; } wp_die();
}

The contact form output displays the contact form layout created with a WordPress template file.

The below screenshots displays the client-side and server-side responses on submitting the form data.

Wordpress Contact Form Outputhttps://phppot.com/wp-content/uploads/20...00x216.png 300w, https://phppot.com/wp-content/uploads/20...68x552.png 768w, https://phppot.com/wp-content/uploads/20...output.png 946w" sizes="(max-width: 550px) 100vw, 550px">

After executing the wp_ajax mail sending action, it returns the boolean response to check the mail is sent or not.

Based on the wp_mail function return data, the AJAX endpoint prepares responses. Figures show the success or the failure response of this WordPress contact form example.

Contact Form Error Responsehttps://phppot.com/wp-content/uploads/20...300x41.png 300w" sizes="(max-width: 469px) 100vw, 469px">

Contact Form Success Responsehttps://phppot.com/wp-content/uploads/20...300x43.png 300w" sizes="(max-width: 465px) 100vw, 465px">

Conclusion


Thus, we have learned how to create a contact form in WordPress. I hope, this will help you to replicate the same in a WordPress website.

We have seen various ways to render contact forms or any layout on the user end. The steps to create a custom contact template may help to build different templates and build customizations.

The code with wp_ajax action hooks defines a section to process contact form data and mail sending.

With this basic idea, it will let you set up a get a quote, project inquiry or any of such form-based UI template in WordPress.

↑ Back to Top



https://www.sickgaming.net/blog/2021/03/...wordpress/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Responsive Contact Form using Foundation Front-end Framework xSicKxBot 0 41 03-02-2021, 08:41 PM
Last Post: xSicKxBot
  [Tut] Responsive Contact Form using Tailwind CSS xSicKxBot 0 85 02-08-2021, 02:30 PM
Last Post: xSicKxBot
  [Tut] Bootstrap Contact Form with JavaScript Validation and PHP xSicKxBot 0 199 09-07-2020, 06:10 PM
Last Post: xSicKxBot
  [Tut] Form Builder – Dike xSicKxBot 0 243 07-24-2020, 09:48 AM
Last Post: xSicKxBot
  [Tut] Contact Form with Custom Image Captcha Validation like Google reCaptcha xSicKxBot 0 300 06-06-2020, 08:21 PM
Last Post: xSicKxBot
  [Tut] User Registration in PHP with Login: Form with MySQL and Code Download xSicKxBot 0 262 06-06-2020, 08:16 AM
Last Post: xSicKxBot
  [Tut] Double Opt-In Subscription Form with Secure Hash using PHP xSicKxBot 0 208 06-03-2020, 02:18 PM
Last Post: xSicKxBot
  [Tut] How to Create Popup Contact Form Dialog using PHP and jQuery xSicKxBot 0 208 06-03-2020, 02:17 AM
Last Post: xSicKxBot
  [Tut] How to Create Popup Contact Form Dialog using PHP and jQuery xSicKxBot 0 374 01-28-2020, 08:01 AM
Last Post: xSicKxBot
  [Tut] Double Opt-In Subscription Form with Secure Hash using PHP xSicKxBot 0 332 01-27-2020, 05:17 AM
Last Post: xSicKxBot

Forum Jump:

[-]
Active Threads
Unigine 2.14 Released
Last Post: xSicKxBot
Today 03:06 PM
» Replies: 0
» Views: 6
News - Lawson Will Offer New Pokémon Sna...
Last Post: xSicKxBot
Today 03:06 PM
» Replies: 0
» Views: 4
News - Nacon Announces WRC 10, Speeds On...
Last Post: xSicKxBot
Today 03:06 PM
» Replies: 0
» Views: 3
News - Blizzard Arcade Collection Gets T...
Last Post: xSicKxBot
Today 03:06 PM
» Replies: 0
» Views: 7
(Indie Deal) FREE Stranded In Time | XCO...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 9
Microsoft - 5 reasons to attend Azure St...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 8
News - Deals: Ring Fit Adventure Is Down...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 9
News - Cuphead Will Have An Awesome Deca...
Last Post: xSicKxBot
Today 07:54 AM
» Replies: 0
» Views: 9
News - Nintendo Actually Responded To A ...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 9
News - Rumour: Dragon Ball Z: Kakarot Co...
Last Post: xSicKxBot
Today 01:50 AM
» Replies: 0
» Views: 9

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020