How do I code a form to email script In WordPress?

Introduction – create a form to email script in WordPress

There are many form plugins for WordPress but how do you actually create a form and then email it using just code? The form we will be creating is shown below it has two name fields, an email and phone field and an enquiry text-area.

You will need access to your theme’s template files, in this case front-page.php and functions.php.

The HTML code for a WordPress form.

The HTML code for the form is shown below this should be placed in the relevant template file, for example front- page.php . The code shown has some Bootstrap classes otherwise it is a conventional form with an ID of “enquiry”. HTML 5 input types are used for the email and phone fields. This ensures that validation will be done in the browser.

<h2>Send an enquiry</h2>
<form id="enquiry">
<div class="form-group row">
    <div class="col-lg-6">
        <input type="text" class="form-control"name="fname" placeholder="First name" required>
    <div class="col-lg-6">
        <input type="text"class="form-control" name="lname" placeholder="Last name" required>
<div class="form-group row">
    <div class="col-lg-6">
        <input type="email" class="form-control" name="email" placeholder="Email address" required>
    <div class="col-lg-6">
        <input type="tel" class="form-control" name="phone" placeholder="Phone" required>
<div class="form-group">
    <textarea name="enquiry" class="form-control"  placeholder="your enquiry" cols="30" rows="10"></textarea>

<div class="form-group">
   <button type="submit" class="btn btn-success btn-block">Send your enquiry</button>

Jquery Ajax form processing

jQuery is used to process the form data. The script below is placed in the same template file as the form. It can also be placed in a separate JS file in the theme.

The script works as follows . Firstly, when the form with an ID of #enquiry is submitted, an anonymous function runs. In the function three variables are setup .

  1. endpoint contains the location of the WordPress script that will deal with any Ajax calls.
  2. form takes the form data object and turns it into a stream of bytes that can be sent over a network (serialise).
  3. formdata instantiates a new object that will be used to store the data from the form as name value pairs.

Next, two items are appended to formdata these add the data from the form to the ajax request that is created later. In the ajax request an array of data is sent to the processing script we added in the endpoint variable. If successful the ajax request returns a success message . An alert is produced to confirm the script is working.

    var endpoint = '<?php echo admin_url('admin-ajax.php');?>';

    var form = jQuery('#enquiry').serialize();

    var formdata  = new FormData;// instantiate object
    formdata.append('action','enquiry');// ajax send object, add action with the ID 0f the form

     type: 'post',
     data: formdata,
     processData: false,
     contentType: false,
     // success is a property of the jQuery ajax object
     success: function(res){

     error: function(err){

Form to email In WordPress – email processing

In functions.PHP an ajax add action hook is used to authorise the use of admin-ajax.php. Normally, for security reasons, this script is blocked from responding to a form unless an action hook exists for it in the theme. In fact two hooks are needed, the “nopriv” hook allows access for non logged in users. The hook uses the ID of the form and the function that runs to process it.

add_action('wp_ajax_enquiry', 'enquiry_form');
add_action('wp_ajax_nopriv_enquiry', 'enquiry_form');

The enquiry_form function is shown below. Firstly we create an empty array that is used to hold the forms “posted” data. The WordPress wp_parse-str() function is used to convert the data back into an array after it was serialised earlier. Next the admin email address is grabbed from the back end. Finally the email headers and subject line are created.

The last part of the script uses a for each loop to parse the array. the wp_mail() function actually sends the mail using the built in functionality of WordPress. A try – catch loop catches any errors.

// Form handling -------------------------------------------------------------------------------------

// listens for an ajax post then runs the enquiry_form function when there is an ajax form call
add_action('wp_ajax_enquiry', 'enquiry_form');
add_action('wp_ajax_nopriv_enquiry', 'enquiry_form');

function enquiry_form(){

  $formdata = [];// create empty array  
  //parse the POSTED data array with an ID of enquiry
  wp_parse_str($_POST['enquiry'], $formdata);

$admin_email = get_option('admin_email');

// email handling and headers--------------------------------------------------------------
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'From: Test site <' . $admin_email . '>';

$send_to = $admin_email;

$subject = 'Enquiry from' . $formdata['fname'] . ' ' .  $formdata['lname']; 

$message = '';
// parse array
foreach($formdata as $index => $field)
      $message .= '<strong>: ' . $index . '</strong>' . $field . '<br/>';
      if(wp_mail($send_to, $subject, $message, $headers))// wordPress mail function
       wp_send_json_success('Email sent');
        wp_send_json_success('Email error');
      }// end else
     catch(Exception $e)

Leave a Reply

Your email address will not be published. Required fields are marked *