Getting Ready
A buil-in WordPress form was initially created on my site PHP Snippets, however, thanks to stupid people who sent hundreds of “test” emails from this form, I have taken it offline.
It looked like this:

Step 1: Creating the page template
The first step is to create a page template. To do so, copy the page.php code into a new file named page-contact.php.
We have to add a comment at the beginning of the contact.php file to make sure WordPress will treat the file as a page template. Here’s the code:
<?php /* Template Name: Contact */ ?>
Your contact.php file should look like this:
<?php /* Template Name: Contact */ ?> <?php get_header() ?> <div id="container"> <div id="content"> <?php the_post() ?> <div id="post-<?php the_ID() ?>" class="post"> <div class="entry-content"> </div><!-- .entry-content -> </div><!-- .post--> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar() ?> <?php get_footer() ?>
Step 2: Building the form
Now, we have to create a simple contact form. Simply paste the following code within the entry-content div.
<form action="<?php the_permalink(); ?>" id="contactForm" method="post"> <ul> <li> <label for="contactName">Name:</label> <input type="text" name="contactName" id="contactName" value="" /> </li> <li> <label for="email">Email</label> <input type="text" name="email" id="email" value="" /> </li> <li> <label for="commentsText">Message:</label> <textarea name="comments" id="commentsText" rows="20" cols="30"></textarea> </li> <li> <button type="submit">Send email</button> </li> </ul> <input type="hidden" name="submitted" id="submitted" value="true" /> </form>
Nothing hard with this pretty self-explanatory html code for our form. Note the input type=”hidden” I added on line 19: It will be used later to check if the form has been submitted.
Step 3: data processing and error handling
Our form looks pretty good, but right it is very useless because it does not send any email. What we have to do is to verify if the form has been submitted then verify if fields have been filled correctly.
If fields are correctly filled, we’ll get the blog admin email and send them the email. Otherwise, no email will be sent and errors will be displayed to the user.
Paste the following code between the Page Template declaration and the get_header() function:
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please 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']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>What I’ve done here was simply to make sure that the form has been submitted and filled correctly. If an error, such as an empty field or incorrect email address occurred, a message is returned and the form isn’t submitted.
Now we have to display error messages below the related field, for example “Please enter your name”. Below you’ll find the complete form page template that you can use “as it”.
<?php
/*
Template Name: Contact
*/
?>
<?php
if(isset($_POST['submitted'])) {
if(trim($_POST['contactName']) === '') {
$nameError = 'Please enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
if(trim($_POST['email']) === '') {
$emailError = 'Please 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']);
}
if(trim($_POST['comments']) === '') {
$commentError = 'Please enter a message.';
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['comments']));
} else {
$comments = trim($_POST['comments']);
}
}
if(!isset($hasError)) {
$emailTo = get_option('tz_email');
if (!isset($emailTo) || ($emailTo == '') ){
$emailTo = get_option('admin_email');
}
$subject = '[PHP Snippets] From '.$name;
$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>
<?php get_header(); ?>
<div id="container">
<div id="content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<p>Thanks, your email was sent successfully.</p>
</div>
<?php } else { ?>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">Sorry, an error occured.<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul class="contactform">
<li>
<label for="contactName">Name:</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="required requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li><label for="commentsText">Message:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
<?php if($commentError != '') { ?>
<span class="error"><?=$commentError;?></span>
<?php } ?>
</li>
<li>
<input type="submit">Send email</input>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
<?php } ?>
</div><!-- .entry-content -->
</div><!-- .post -->
<?php endwhile; endif; ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>Step 4: Adding jQuery verification
Our form is now working perfectly. But we can enhance it by adding a client side verification. To do so, I’m going to use jQuery and the validate jQuery plugin. This plugin is great because it allows you to verify that a form has been filled correctly, quickly and easily.
The first thing to do is to download the validate plugin and upload it into your theme file (under a /js directory). Once done, paste the following into a new file:
$(document).ready(function(){
$("#contactForm").validate();
});Save it as verif.js in your /js directory.
Now we have to link the javascript files to our theme. Open your header.php file and paste the following within the <head> and </head> tags:
<?php if( is_page('contact') ){ ?>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script>
<?php }?>Once done, your form will be validated on the client side by the jQuery validate plugin. How does it work? It simply picks form element which have the css class required and verifies if they’re filled correctly. If not, a message is displayed.
The plugin is powerful and you can do lots of things with it, however this isn’t the purpose of this article. Hope you enjoy your new WordPress form!






My name is Jean-Baptiste Jung and I'm the man behind Cats Who Code. I started to use the Internet back in 1998 and started to create websites three years laters in 2001.
45 Comments
Nice tutorial, really better using this than a Cform or other plug-ins.
Thank you. I was looking for this information for so long
This is an awesome tutorial. I was also annoyed with the extra options and terrible code that contact form plugin makers use in there code.
This is a simple code and looks like it works well. thanks so much.
Nice tutorial… one minor objection: you should drop eregi this function has been deprecated by PHP you should use preg_match instead. But like I say a minor objection on a great tutorial
Agreed, that’s the first thing I noticed when I was looking through this post. Really, really you should update this code to use preg_match, but other than that, good tutorial.
Some people have the opinion that any generic block of functionality such as this should be encapsulated in a plugin for consumption, but it is not as clear cut as that, as your example demonstrates. It makes much more sense to use a theme template page instead, rather than use a plugin.
Cool! Don’t have to rely on plugins as much for simple contact forms.
Hi jean
Great tutor I also need tutorial to customize comment form with out any plugin…
Nice tutorial, similar approach as i had in my WordPress contact form tutorial which has ajax submission and validation without a plugin. http://wpcanyon.com/tutorials/creating-a-contact-page-from-scratch-in-wordpress/
Anyway, shouldn’t we use jQuery instead of $ when we work with jQuery in WordPress?
Awesome post dude I got a try it on my new upcoming web site.
Thanks
Hey, You have copied this stuff from this page:
techtipsgeek.com/install-contact-page-in-wordpress-blog-without-plugin/6664/
Didn’t knew about this site before.
I agree that my tutorial is about the same subject but I haven’t copied anything. Anyways, there’s a lot of bad coding practices in your link.
Thanks for your clarification. I appreciate that you are bold enough to tolerate positive and negative criticism. Anyways good work.
This is fantastic. I hate using too many plugins and have recently switched to using my own contact forms.
I would add in case others didn’t catch why you use “contactName” instead of just “name” that you cannot use “name” when submitting forms on WP sites or it will conflict with something. I had a real problem with that once and finally caught that tip in a blog somewhere!
Now a great follow up to this tut would be to show how you can insert this data into a new table in the WP database using the wpdb.
That’s a great tutorial but I thought it’s gonna be a small time affair
Looks like it’s better to go with a plugin like contact form 7 which is completely customizable?
I srrsly love you for this.. how long I wanted to have something like this that works so great.
Very nice blog btw, alot of helpfull articles that really contribute to the Wordpress community
This is a great tutorial, I have never like the generic forms that plug-ins offers. Some personal touch on this code can make miracles and for sure will guarantee better communication.Thanks for contribution again to Wordpress community.
why not using the wordpress built-in wp_mail()?
wp_mail() is located in wp-includes/plugable.php and uses the known phpmailer class.
regards
You’re right, I should have used wp_mail(). Thanks for the notice.
Will this also work if you are using a child theme with Thematic? Are there any changes I would need to make for it to work with a child theme? Thanks!
Yes, it will work perfectly (I’m using Thematic on most of my sites). No changes, just put the page template in your child theme directory.
I keep getting an error at line 1
Is this form secure from XSS and other stuff ?
I am also using plug-in contact form but i was planning to change. Thanks for tutorial.
Thanks a lot for this tutorial post!
I was looking for a great tutorial to learn how to create a custom Wordpress Contact Form from Scratch.
I shared this post on my Tumblog.
Keep posting!
Awesome! Tested, works fine.
Thanks a lot for sharing.
thanks the article!
I’ve been hacking into the page template to achieve this, your answer is so simple and easily portable I’ve already used it on a new site.
Is there any spam protection for this form though as we get a lot of comment spam bots crawling our sites?
Thanks, spent 5 or 6h on my form until I realized I could Google it
Thanks for posting this detailed and step-by-step tutorial. Tested it, it’s working fine.
Great tutorial! I was wondering, when a message is sent to my email it says it’s from “me”; how would you change it so it says the name of the person who sent the message, instead?
This was really a knowledgeable post…Expecting more posts like this.
I’m a new in wordpress, this is nice tutorial and help me a lot. just one question, how to put captcha on it? I realize there is a captcha if statement in the code.
Nice post. I like to do all handmade
Hi. I tried this code to implement a captcha but it donesn´t runs, do you know if there is some problem with your script?
Maybe you can help me out, how come the contact form will not work with the permalinks on? Is there a way around this?
Hi Jean-Baptiste,
First of all, merci beaucoup, this is the best Contact Form code I’ve even seen! Like many others already said, I’ve been looking for such a code for years, plugins have bugs or use way too many resources…
So I will definitely use your code for my personal website but I have several questions:
- Will you update your code using ‘preg_match’ like nyamsprod and Nate suggested? Same question for using the wordpress built-in wp_mail() suggested by HerrZ?
- Boba asked if you shouldn’t use jQuery instead of $ when we work with jQuery in WordPress. What do you think?
- nackle and carlos are asking about how to integrate Captcha code in the form. Could you please give us a hint on how to do that?
- And I have one question: can you please explain how to add multiple form recipient (drop down list: Authors, Webmaster, etc)?
I hope I’m not asking too much but your code is almost perfect and if you could add those suggested updates/modifications, it would be legendary!
Encore merci!!
Great stuff, nice to know this and how to do it will help wordpress bloggers everywhere.
I was also annoyed with the extra options and terrible code. So I will definitely use your code for my personal website
Thanks for the great info!
Unfortunately it’s the technical issues that hold me back most of the time and step by step tutorials are a huge help.
Thanks again,
Lesley
Congratulations, good article!
I think it is easier to use a plug-in, at least for me it is easier
Thank you for this wonderful tutorial!
Wow! What a very detailed and clear tutorial. For a not too techie like me, you just make it a very simple one. Thanks for this! I’ll use this in my websites.
I have never like the generic forms that plug-ins offers.
Great tutorial and I will have to give it a try. I am not a great techie person but I am still in the learning phase. We all have to start somewhere.
5 Trackbacks
[...] How to create a built-in contact form for your WordPress theme. VN:F [1.7.7_1013]please wait…Rating: 0.0/10 (0 votes [...]
[...] 1. How to create a built-in contact form for your WordPress theme. Many WordPress plugins can add a contact form to your blog, but a plugin is not necessary. In this [...]
[...] How to create a built-in contact form for your WordPress theme Built-In Contact form for wordpress [...]
[...] How to create a built-in contact form for your WordPress theme %CONTENT% [...]
[...] avoid boring anouncement posts and introduce your new blog on a more subtle way. A good example is this post I wrote on CatsWhoCode, which used my other site PHP Snippets as a live [...]