How to Code Your Own WordPress Contact Form with jQuery Validation

Posted OnApr 14, 2015     CategoryDevelopment     CommentsNo comment

Regardless of what you use WordPress for, there’s a range of common functions people need their site to perform that aren’t bundled with WordPress. This leaves you with two choices, installing a plugin or creating it yourself.

In this article we’re going to show you how to create a commonly sought after feature that most sites require, a contact form that sends email to the WordPress Admin, and we’re going to do it by extending a theme. That said, you could also take this approach and do it through a plugin.

Creating a Child Theme and Contact Template

To extend the functionality of your theme we can create a child theme. To create a child theme create a folder called twentytwelvecontactformchild in the wp-content/themes directory of your WorPress installation. Once you have created the directory you will have to create a file called style.css in it with the following code:

/*
Theme Name:     Twenty twelve child to add contact form
Theme URI:      
Description:    Child theme to demo how to add a contact form in the theme.
Author:         Abbas S
Template:       twentytwelve
Version:        1.0
*/

@import url("../twentytwelve/style.css");

style.css lets you define your child theme attributes like theme name, description, and the template – which is the base theme, in this case twentytwelve, but you can use any of your choice. Then we import the style.css of the base theme so that we get all the styles from the base theme. Once we have done this we should be able to see our theme as shown below:

Child Theme created and working

Now we will create a page template for our ‘Contact Us’ page. To create a page template, create a file called contactform.php in the child theme folder with the following content (note the div and ids of the primary and content section may differ depending on the base theme you are using).

<?php
/*
Template Name: Contact
*/
?>

<?php get_header(); ?>

	<div id="primary" class="site-content">
		<div id="content" role="main">

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

In this we’ve added the commented header to declare this file as a page template with the name as ‘Contact’. Then we have added some basic boilerplate code to get the header and footer for WordPress. You can read more about custom page templates on the Codex.

Once done you can create a page called Contact Us in your WordPress Dashboard and use this page template as shown below:

image003

Showing the Contact Form on the Contact Template

Once we have added the contact template, lets move on and create the contact form for the page template. To do that we will create a file contactformhandler.php with the following code:

<?php

class ContactFormHandler {

	function handleContactForm() {
 			$this->displayContactForm();
    }
   
	//This function displays the Contact form.
    public function displayContactForm() {
    	?>
    	<div id ="contactFormSection">
	    	<form action="" id="contactForm" method="POST" enctype="multipart/form-data">
	 
			    <fieldset>
			        <label for="name">Your Name</label>
			 
			        <input type="text" name="contactname" id="contactname" />
			    </fieldset>

			    <fieldset>
			        <label for="email">Your Email</label>
			 
			        <input type="text" name="contactemail" id="contactemail" />
			    </fieldset>
			 
			    <fieldset>
			        <label for="content">Contents</label>
			 
			        <textarea name="contactcontent" id="contactcontent" rows="10" cols="35" ></textarea>
			    </fieldset>
			 
			    <fieldset>
			        <button type="submit" name="submitContactForm" >Send Query</button>
			    </fieldset>

			    <?php wp_nonce_field( 'submit_contact_form' , 'nonce_field_for_submit_contact_form'); ?>
	 
			</form>
		</div>
		<?php
    }
   
}

?>

In the above code we have created a class ContactFormHandler with two functions; handleContactForm, which currently just calls the other function displayContactForm which displays an HTML form with the fields to add the name, email and contact query.

Now we will update our page template contactform.php to use this class to display the form as shown in below code

<?php
/*
Template Name: Contact
*/
?>

<?php require "contactformhandler.php"; ?>
<?php get_header(); ?>

	<div id="primary" class="site-content">
		<div id="content" role="main">

			<?php 
				$wpContactFormObj = new ContactFormHandler();  
				$wpContactFormObj->handleContactForm(); 
			?>

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Once we have added this code we should be able to go to the contact us page and see the form as below

Contact for now displaying

Styling the Contact Form

Once we have created the form, we can add some styles to it. To do that we will have to load a CSS file which styles the different elements in the form. To do that, we will create a file called functions.php in our child theme folder with the following code:

<?php

 function contactform_add_scripts() {
	    // Register the style for the Contact form
	    wp_register_style( 'contactform-style',  get_stylesheet_directory_uri(). '/contactform.css');
	    wp_enqueue_style( 'contactform-style' );

	}


 //Add CSS and other scripts for the Contact form.
 add_action('wp_enqueue_scripts', contactform_add_scripts);

In the above code we added a function with the WordPress hook wp_enqueue_scripts which should be used if we have some scripts to be enqueued. In the function contactform_add_scripts we register our css file contactform.css with the url as that of the child theme directory which will be dynamically retrieved with the WordPress API hook get_stylesheet_directory_uri.

Once we have enqueued the script WordPress will load this CSS file. Now we actually create the file contactform.css and add the following code to it to style the form:

#contactFormSection  input, #contactFormSection textarea { 
    padding: 9px; 
    border: dotted 2px #66FFFF; 
    outline: 0; 
    font: normal 13px/100% Verdana, Tahoma, sans-serif; 
    width: 200px; 
    background: #FFFFFF; 
    margin-top: 10px;

    } 
   
#contactFormSection  textarea { 
    width: 500px; 
    height: 150px; 
    line-height: 150%; 
    } 
   
#contactFormSection  input:hover, #contactFormSection textarea:hover, 
#contactFormSection input:focus, #contactFormSection textarea:focus { 
    border-color: #3399FF; 
    } 
   
#contactFormSection  label { 
    margin-left: 10px; 
    color: #999999; 
   
    } 
   
#contactFormSection  button { 
    width: auto; 
    padding: 15px; 
    background: #617798; 
    border: 0; 
    font-size: 14px; 
    color: #FFFFFF; 
    float:right;
    margin-top: 10px;
 }

You are of course welcome to style it as you see fit. Now if you load the form it will look as shown below

Styled contact form

Adding Client Validation

Now that we have built the form, we can add the validation to the form so that wrong data does not get passed through. Here we will do both client side validation using jQuery, and server side validation in PHP. It’s generally a good practice to do validations on both the side as client side validation help the user to know if any error in the form immediately on the client side without taking a complete round trip to the server. Server side validations are also necessary so that no one can post malicious data to the server script directly.

To do the client side validation we will use the jQuery validation plugin which lets you validate forms by specifying simple rules. To do this we download the jQuery validation plugin and add to our child theme folder. We now update the functions.php as shown below to add the jQuery validation script and our custom script, contactform.js

<?php

 function contactform_add_scripts() {
	    // Register the style for the Contact form
	    wp_register_style( 'contactform-style',  get_stylesheet_directory_uri(). '/contactform.css');
	    wp_enqueue_style( 'contactform-style' );

	    wp_register_script( 'jquery-validate-script', get_stylesheet_directory_uri() . '/jquery.validate.min.js' ,array( 'jquery'));
 	    wp_enqueue_script( 'jquery-validate-script' );

	    wp_register_script( 'contactform-script', get_stylesheet_directory_uri() . '/contactform.js' ,array( 'jquery','jquery-validate-script'));
 	    wp_enqueue_script( 'contactform-script' );

	}

//Add CSS and other scripts for the Contact form.
 add_action('wp_enqueue_scripts', contactform_add_scripts);

Then we will add the rules for jQuery validation plugin in contactform.js as shown below

jQuery(document).ready(function($) {
	  $( "#contactForm" ).validate({
	  rules: {
	      contactname: {
	      required: true
	    },
	    contactemail: {
	      required: true,
	      email: true
	    },
	    contactcontent: {
	      required: true
	    }
	  }
	});
})

In the above code we make the three fields required as true and also add email validation for contactemail field. Once you have done this if you post the form without adding of the values you will see the error as shown below

validation added to the contact form

Adding Server Side Validation

To add server side validations we add the change the function handleContactForm and add other functions to our class ContactFormHandler as below

	function handleContactForm() {
    
		if($this->isFormSubmitted() && $this->isNonceSet()) {
			if($this->isFormValid()) {
				$this->sendContactForm();
			} else {
				$this->displayContactForm();
			}
		} else {
			$this->displayContactForm();
		}

    }

    public function sendContactForm() {
    }

    function isNonceSet() {
    	if( isset( $_POST['nonce_field_for_submit_contact_form'] )  &&
    	  wp_verify_nonce( $_POST['nonce_field_for_submit_contact_form'], 'submit_contact_form' ) ) return true;
    	else return false;
    }

    function isFormValid() {
    	//Check all mandatory fields are present.
		if ( trim( $_POST['contactname'] ) === '' ) {
			$error = 'Please enter your name.';
			$hasError = true;
		} else if (!filter_var($_POST['contactemail'], FILTER_VALIDATE_EMAIL)  ) {
			$error = 'Please enter a valid email.';
			$hasError = true;
		} else if ( trim( $_POST['contactcontent'] ) === '' ) {
			$error = 'Please enter the content.';
			$hasError = true;
		} 

		//Check if any error was detected in validation.
		if($hasError == true) {
			echo $error;
			return false;
		}
		return true;
    }

 	function isFormSubmitted() {
    	if( isset( $_POST['submitContactForm'] ) ) return true;
    	else return false;
    }

In the above code, we first check if the form is submitted in the function isFormSubmitted by checking if the post variable submitContactForm is set or not, and then we verify the Nonce set in the function isNonceSet.

Once that is done in the function isFormValid we do the validation of the different required fields and the email validation and then call the sendContactForm whose implementation we will see in the next section.

Sending the Contact Us email

Once the form is validated the function sendContactForm is called which should be implemented as follows

public function sendContactForm() {
    	$contactName = $_POST['contactname'] ;
    	$contactEmail = $_POST['contactemail'];
    	$contactContent = $_POST['contactcontent'];

    	$emailTo = get_option( 'admin_email');


    	$subject = 'New contact from  From '.$contactName;
		$body = "Contact Name: $contactName \n\nContact Email: $contactEmail \n\nContact contents: $contactContent";
		$headers = 'From: '.$contactName.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $contactEmail;

		wp_mail($emailTo, $subject, $body, $headers);

		echo "Contact Us sent. We will reply to your query soon.";
		
    }
    

In the above function we read the contact information from the _POST variable for the data posted in the form. We get the admin email to which the contact details are to be mailed using the WordPress function get_option. Then we send the mail using the WordPress function wp_mail.

Conclusion

WordPress lets you customize its functionality and add functionality to suit the needs of your site. In the article above we saw how to create a contact template to add a contact form to your WordPress site. So have fun creating on your next WordPress site ☺.


Leave a Reply

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

Send this to friend