<p>There are <a href="http://wordpress.org/extend/plugins/search.php?q=contact">lots of WordPress plugins for contact forms</a>, but wouldn’t it be nice to have more control over the markup? In this tutorial, I am going to show how to use a custom page template to create a contact form in WordPress without a plugin.</p>
<p>Some people may want to skip the post and get to the demo and source files:</p><p class="clearfix"><a href="http://wp.trevor-davis.com/contact-form/" class="leftSide more-link">View Demo</a> <a href="//trevor-davis.com/images/content/2009/02/contact-form.zip" class="leftSide more-link">Download Source Files</a></p><h2>So, why not use a plugin?</h2><p>Well, I think that a contact form is so simple that a WordPress plugin that doesn’t provide exactly what I want is pretty lame. Plus, I don’t need all those fancy interfaces for building the form; I just need the code.</p><h2>The Plan</h2><p>Our plan is to create a custom <a href="http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates">WordPress Page Template</a>, then create a page that uses that template. Finally, we will add in a little <strong>jQuery</strong> to improve the form. Let’s write a little pseudo code to help determine how our page template will be structured.</p><h3>Pseudo Code</h3>
<pre>&lt;code&gt;If form was submitted validate it
 If the form was submitted successfully
  Send email(s)
 Else
  Set variables to show errors

If the form was submitted successfully
 Show thank you message
Else
 Show form (with errors if there are any)</pre>
<h3>Creating the WordPress Page Template</h3><p>Alright, so first, we are going to start with some basic stuff: define the template name, include the header/sidebar/footer, and setup the basic structure of our pseudo code.</p><pre>&lt;code&gt;&lt;?php
/*
Template Name: Contact Form
*/
?&gt;

&lt;?php 
//If the form is submitted
if(isset($_POST['submitted'])) {
 //If there is no error, send the email
 if(!isset($hasError)) {

 }
} ?&gt;

&lt;?php get_header(); ?&gt;

&lt;?php 
//If the email was sent, show a thank you message
//Otherwise show form
if(isset($emailSent) &amp;&amp; $emailSent == true) {
?&gt;

&lt;?php } else { ?&gt;

&lt;?php } ?&gt;

&lt;?php get_sidebar(); ?&gt;

&lt;?php get_footer(); ?&gt;</pre>
<h3>The Form</h3><p>Next, let’s code the actual form. I also want to provide the ability for the user to enter some text to go above the form, so we are going to use the regular loop:</p>
<pre>&lt;code&gt;&lt;?php if(isset($emailSent) &amp;&amp; $emailSent == true) { ?&gt;

 &lt;div class="thanks"&gt;
  &lt;h1&gt;Thanks, &lt;?=$name;?&gt;&lt;/h1&gt;
  &lt;p&gt;Your email was successfully sent. I will be in touch soon.&lt;/p&gt;
 &lt;/div&gt;

&lt;?php } else { ?&gt;

 &lt;?php if (have_posts()) : ?&gt;
 
  &lt;?php while (have_posts()) : the_post(); ?&gt;
   &lt;h1&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
   &lt;?php the_content(); ?&gt;
  
   &lt;?php if(isset($hasError) || isset($captchaError)) { ?&gt;
    &lt;p class="error"&gt;
     There was an error submitting the form.
    &lt;p&gt;
   &lt;?php } ?&gt;
 
   &lt;form action="&lt;?php the_permalink(); ?&gt;" id="contactForm" method="post"&gt;
 
   &lt;/form&gt;
 
  &lt;?php endwhile; ?&gt;
 &lt;?php endif; ?&gt;
&lt; } ?&gt;</pre>
<p>If the <strong>emailSent</strong> variable is set to true, we display the thank you message. Otherwise, we show the form. So we are outputting the title of the page, and any content that was entered. Then, we are checking to see if there was an error. Finally, we display the form:</p><pre>&lt;code&gt;&lt;ol class="forms"&gt;
 &lt;li&gt;
  &lt;label for="contactName"&gt;Name&lt;/label&gt;
  &lt;input type="text" name="contactName" id="contactName" value="
  &lt;?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?&gt;"
   class="requiredField" /&gt;
  &lt;?php if($nameError != '') { ?&gt;
   &lt;span class="error"&gt;&lt;?=$nameError;?&gt;&lt;/span&gt; 
  &lt;?php } ?&gt;
 &lt;/li&gt;
 
 &lt;li&gt;
  &lt;label for="email"&gt;Email&lt;/label&gt;
  &lt;input type="text" name="email" id="email" value="
  &lt;?php if(isset($_POST['email']))  echo $_POST['email'];?&gt;"
  class="requiredField email" /&gt;
  &lt;?php if($emailError != '') { ?&gt;
   &lt;span class="error"&gt;&lt;?=$emailError;?&gt;&lt;/span&gt;
  &lt;?php } ?&gt;
 &lt;/li&gt;
 
 &lt;li class="textarea"&gt;
  &lt;label for="commentsText"&gt;Comments&lt;/label&gt;
  &lt;textarea name="comments" id="commentsText" rows="20" cols="30" class="requiredField"&gt;
  &lt;?php if(isset($_POST['comments'])) { 
   if(function_exists('stripslashes')) { 
    echo stripslashes($_POST['comments']); 
   } else { 
    echo $_POST['comments']; 
   }
   } ?&gt;&lt;/textarea&gt;
  &lt;?php if($commentError != '') { ?&gt;
   &lt;span class="error"&gt;&lt;?=$commentError;?&gt;&lt;/span&gt; 
  &lt;?php } ?&gt;
 &lt;/li&gt;
 &lt;li class="inline"&gt;
  &lt;input type="checkbox" name="sendCopy" id="sendCopy" value="true"
  &lt;?php if(isset($_POST['sendCopy']) &amp;&amp; $_POST['sendCopy'] == true) 
   echo ' checked="checked"'; ?&gt; 
  /&gt;
  &lt;label for="sendCopy"&gt;Send a copy of this email to yourself&lt;/label&gt;
 &lt;/li&gt;
 &lt;li class="screenReader"&gt;
  &lt;label for="checking" class="screenReader"&gt;If you want to submit this form, do not enter anything in this field&lt;/label&gt;
  &lt;input type="text" name="checking" id="checking" class="screenReader" value="
  &lt;?php if(isset($_POST['checking']))  echo $_POST['checking'];?&gt;"
  /&gt;
 &lt;/li&gt;
 &lt;li class="buttons"&gt;
  &lt;input type="hidden" name="submitted" id="submitted" value="true" /&gt;
  &lt;button type="submit"&gt;Email me »&lt;/button&gt;
 &lt;/li&gt;
&lt;/ol&gt;</pre>
<p class="note"><em>Note: Line wrapping added for readability.</em></p><p>Ok, wow, that may seem like a lot. So let’s break down the name field to see what this code is actually doing:</p><pre>&lt;code&gt;&lt;li&gt;&lt;label for="contactName"&gt;Name&lt;/label&gt;
 &lt;input type="text" name="contactName" id="contactName" value="&lt;?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?&gt;" class="requiredField" /&gt;
 &lt;?php if($nameError != '') { ?&gt;
  &lt;span class="error"&gt;&lt;?=$nameError;?&gt;&lt;/span&gt; 
 &lt;?php } ?&gt;
&lt;/li&gt;</pre>
<p>We are displaying each form field in a list item, displaying the label, input field, and then showing an error message if there is one. We are also displaying the value in the form field if it was already submitted.</p><p>So in essence, we are just doing that for each field of the form. You could easily go into the code to add more fields.</p><p>We are also using honeypot captcha to see if a bot was trying to submit the form:</p><pre>&lt;code&gt;&lt;li class="screenReader"&gt;
 &lt;label for="checking" class="screenReader"&gt;If you want to submit this form, do not enter anything in this field&lt;/label&gt;
 &lt;input type="text" name="checking" id="checking" class="screenReader" value="&lt;?php if(isset($_POST['checking']))  echo $_POST['checking'];?&gt;" /&gt;
&lt;/li&gt;</pre>
<p>That list item is pushed off the page with CSS, and if there is a value in that field, we can assume that it is not a human trying to submit the form:</p><pre>&lt;code&gt;.screenReader { 
 left: -9999px; 
 position: absolute; 
 top: -9999px;
}</pre>
<h3>The Validation</h3><p>Next, we are going to have a conditional statement to determine if the form was submitted or not:</p><pre>&lt;code&gt;&lt;?php 
//If the form is submitted
if(isset($_POST['submitted'])) {

} ?&gt;</pre>
<p>Within that conditional, is where we are going to do all of our validation of the required fields. First, let’s check to see if our honeypot captcha form field is filled in. If it is, then we will display an error and not check anymore of the form:</p><pre>&lt;code&gt;//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
 $captchaError = true;
} else {

}</pre>
<p>So if the captcha field was left blank, we will continue to validate the required fields:</p><pre>&lt;code&gt;//Check to make sure that the name field is not empty
if(trim($_POST['contactName']) === '') {
 $nameError = 'You forgot to enter your name.';
 $hasError = true;
} else {
 $name = trim($_POST['contactName']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) === '')  {
 $emailError = 'You forgot to enter your email address.';
 $hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+.[A-Z]{2,4}$", trim($_POST['email']))) {
 $emailError = 'You entered an invalid email address.';
 $hasError = true;
} else {
 $email = trim($_POST['email']);
}
 
//Check to make sure comments were entered 
if(trim($_POST['comments']) === '') {
 $commentError = 'You forgot to enter your comments.';
 $hasError = true;
} else {
 if(function_exists('stripslashes')) {
  $comments = stripslashes(trim($_POST['comments']));
 } else {
  $comments = trim($_POST['comments']);
 }
}</pre>
<p>Again, that may seem like a little much, so let’s just take a look at the validation on the name field:</p><pre>&lt;code&gt;if(trim($_POST['contactName']) === '') {
 $nameError = 'You forgot to enter your name.';
 $hasError = true;
} else {
 $name = trim($_POST['contactName']);
}</pre>
<p>If the name field if empty, set a variable that will display the name error and set a flag saying that there was an error on the form. Otherwise, set a variable that will contain the name value from the form.</p><h3>Sending the Email</h3><p>Now, we want to send the email if there are no errors:</p>
<pre>&lt;code&gt;//If there is no error, send the email
if(!isset($hasError)) {

 $emailTo = '&lt;strong&gt;me@somedomain.com&lt;/strong&gt;';
 $subject = 'Contact Form Submission from '.$name;
 $sendCopy = trim($_POST['sendCopy']);
 $body = "Name: $name nnEmail: $email nnComments: $comments";
 $headers = 'From: My Site &lt;'.$emailTo.'&gt;' . "rn" . 'Reply-To: ' . $email;
 
 mail($emailTo, $subject, $body, $headers);

 if($sendCopy == true) {
  $subject = 'You emailed &lt;strong&gt;Your Name&lt;/strong&gt;';
  $headers = 'From: &lt;strong&gt;Your Name&lt;/strong&gt; &lt;&lt;strong&gt;noreply@somedomain.com&lt;/strong&gt;&gt;';
  mail($email, $subject, $body, $headers);
 }

 $emailSent = true;

}</pre>
<p class="note"><em>Note: Items bolded are values that you will want to change before implementing.</em></p><p>I personally like to have the contact form submission come from myself. That way, I just setup a filter in Gmail, and I can guarantee that it won’t get caught in my spam filter. The second email is only sent if the user checks the checkbox to send a copy to themselves.</p><p><a href="//trevor-davis.com/images/content/2009/02/contact-form.txt" class="more-link">View Entire Custom Page Template</a></p><h3>Creating the Page in WordPress</h3><p>First, you want to upload the <a href="//trevor-davis.com/images/content/2009/02/contact-form.zip">contact-form.php</a> page template to your themes folder. Next, you will create the page in WordPress and select <strong>Contact Form</strong> as the page template.</p><p class="pullLeft"><img src="//trevor-davis.com/images/content/2009/02/wordpress-page-template.png" alt="Adding WordPress page template" class="frame" height="341" width="570" /></p><p>Then, just publish your page and you will have your contact form. Well, the form will be usable, but we are going to add in some CSS and jQuery to finish it off.</p><h3>Styling the Form</h3><p>I recently wrote <a href="//trevor-davis.com/blog/tutorial/flexible-and-semantic-forms-with-a-little-jquery/">an article about styling forms</a>, so we are just going to stick with some basic styles:</p><pre>&lt;code&gt;.screenReader { left: -9999px; position: absolute; top: -9999px; }
.thanks { background: #F2F3F6; border: 1px solid #7E8AA2; padding: 10px; }

/*****Forms*****/
ol.forms { float: left; list-style: none; margin: 0; width: 100%; }
ol.forms li { 
 clear: both; 
 float: left; 
 margin-bottom: 18px; 
 position: relative;
 width: 100%;
}
ol.forms label {
 cursor: pointer;
 display: block;
 float: left;
 font-weight: bold;
 padding-right: 20px;
 width: 100px;
}
ol.forms input, ol.forms textarea {
 border: 1px solid #7E8AA2;
 border-radius: 3px;
 font: inherit;
 -moz-border-radius: 3px;
 padding: 2px;
 -webkit-border-radius: 3px;
 width: 214px;
}
ol.forms textarea { height: 300px; width: 334px; }
ol.forms input:focus, ol.forms textarea:focus { background-color: #f2f3f6; border-color: #ff9800; }
.error { color: #f00; }
ol.forms li .error { font-size: 12px; margin-left: 20px; }
ol.forms li.textarea .error {
 display: block;
 position: absolute;
 right: 0;
 top: 0;
 width: 100px;
}
ol.forms li.screenReader { margin-bottom: 0; }
ol.forms li.buttons button {
 background: #ff9800;
 border: none;
 color: #000;
 cursor: pointer;
 font: 16px/16px "Avenir LT Std", Helvetica, Arial, sans-serif;
 overflow: hidden;
 padding: 6px 3px 3px 3px;
 text-transform: uppercase;
 width: auto;
}
ol.forms li.buttons button:hover { color: #222; }
ol.forms li.buttons button:active { left: -1px; position: relative; top: -1px; }
ol.forms li.buttons, ol.forms li.inline { float: right; width: 460px; }
ol.forms li.inline input { width: auto; }
ol.forms li.inline label { display: inline; float: none; width: auto; }</pre>
<p>So drop that CSS in your theme stylesheet and you will see the form start to look much better.</p><h3>Enhancing the form with some jQuery</h3><p>I have also already written about creating <a href="//trevor-davis.com/blog/ajax-forms-with-jquery/">AJAX forms with jQuery</a>, but I thought I would specifically talk about an AJAX script for a contact form.</p><p>First, we want to execute our jQuery when the document is ready and the form was submitted:</p><pre>&lt;code&gt;$(document).ready(function() {
 $('form#contactForm').submit(function() {
  
  return false;
 });
});</pre>
<p>Next, we want to hide any error messages if there are any and validate any required fields which are denoted with a class of <strong>requiredField</strong>:</p><pre>&lt;code&gt;$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {
   
});</pre>
<p>After that, we want to validate that the field is not empty and append an error message if it is:</p><pre>&lt;code&gt;if(jQuery.trim($(this).val()) == '') {
 var labelText = $(this).prev('label').text();
 $(this).parent().append('&lt;span class="error"&gt;You forgot to enter your '+labelText+'.&lt;/span&gt;');
 hasError = true;
}</pre>
<p>If the field is not empty and also has a class of <strong>email</strong>, we want to validate that the email address is valid:</p><pre>&lt;code&gt; else if($(this).hasClass('email')) {
 var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
 if(!emailReg.test(jQuery.trim($(this).val()))) {
  var labelText = $(this).prev('label').text();
  $(this).parent().append('&lt;span class="error"&gt;You entered an invalid '+labelText+'.&lt;/span&gt;');
  hasError = true;
 }
}</pre>
<p>If there are no errors, then we want to replace the submit button with a loading image:</p><pre>&lt;code&gt;if(!hasError) {
$('form#contactForm li.buttons button').fadeOut('normal', function() {
 $(this).parent().append('&lt;img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" /&gt;');
});</pre>
<p class="note"><em>Note: You will need to update the source of the image to wherever you upload it in your theme.</em></p><p>Finally, let’s submit the form via an AJAX request, slide the form up, and show a thank you message:</p><pre>&lt;code&gt;var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
 $('form#contactForm').slideUp("fast", function() {       
  $(this).before('&lt;p class="thanks"&gt;&lt;strong&gt;Thanks!&lt;/strong&gt; Your email was successfully sent. I check my email all the time, so I should be in touch soon.&lt;/p&gt;');
 });
});</pre>
<p>Take a look at the entire script:</p><pre>&lt;code&gt;$(document).ready(function() {
 $('form#contactForm').submit(function() {
  $('form#contactForm .error').remove();
  var hasError = false;
  $('.requiredField').each(function() {
   if(jQuery.trim($(this).val()) == '') {
    var labelText = $(this).prev('label').text();
    $(this).parent().append('&lt;span class="error"&gt;You forgot to enter your '+labelText+'.&lt;/span&gt;');
    hasError = true;
   } else if($(this).hasClass('email')) {
    var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
    if(!emailReg.test(jQuery.trim($(this).val()))) {
     var labelText = $(this).prev('label').text();
     $(this).parent().append('&lt;span class="error"&gt;You entered an invalid '+labelText+'.&lt;/span&gt;');
     hasError = true;
    }
   }
  });
  if(!hasError) {
   $('form#contactForm li.buttons button').fadeOut('normal', function() {
    $(this).parent().append('&lt;img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" /&gt;');
   });
   var formInput = $(this).serialize();
   $.post($(this).attr('action'),formInput, function(data){
    $('form#contactForm').slideUp("fast", function() {       
     $(this).before('&lt;p class="thanks"&gt;&lt;strong&gt;Thanks!&lt;/strong&gt; Your email was successfully sent. I check my email all the time, so I should be in touch soon.&lt;/p&gt;');
    });
   });
  }
  
  return false;
  
 });
});</pre>
<p>Just include it in the head of your document after jQuery, and you are good to go:</p><pre>&lt;code&gt;&lt;script type="text/javascript" src="&lt;?php bloginfo('template_directory'); ?&gt;/scripts/jquery.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="&lt;?php bloginfo('template_directory'); ?&gt;/scripts/contact-form.js"&gt;&lt;/script&gt;</pre>
<p class="note"><em>Note: You may need to change the source depending upon where you upload the files in your theme.</em></p><h2>Conclusion</h2><p class="clearfix"><a href="http://wp.trevor-davis.com/contact-form/" class="leftSide more-link">View Demo</a> <a href="//trevor-davis.com/images/content/2009/02/contact-form.zip" class="leftSide more-link">Download Source Files</a></p><p>That’s it! Just upload the files and you’ve got your form. Since you’ve got the code right in front of you, it should be very easy to tweak and add on to. Enjoy!</p><p class="ad">
CenturyLink Deals: <a href="http://www.centurylinkquote.com/bundles.html">Internet, Phone, &amp; TV Bundles</a></p>