Many WordPress plugins can add a contact form to your blog, but a plugin is not necessary. In this tutorial, I'm going to show you how you can create a built-in contact form for your WordPress theme.

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!

 

45 Comments

  1. Posted June 28, 2010 at 10:47 am | Permalink

    Nice tutorial, really better using this than a Cform or other plug-ins.

  2. Posted June 28, 2010 at 11:56 am | Permalink

    Thank you. I was looking for this information for so long

  3. Posted June 28, 2010 at 12:15 pm | Permalink

    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.

  4. Posted June 28, 2010 at 1:10 pm | Permalink

    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 ;)

    • Posted July 19, 2010 at 5:45 pm | Permalink

      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.

  5. Posted June 28, 2010 at 1:42 pm | Permalink

    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. :)

  6. Posted June 28, 2010 at 1:53 pm | Permalink

    Cool! Don’t have to rely on plugins as much for simple contact forms.

  7. Posted June 28, 2010 at 2:13 pm | Permalink

    Hi jean
    Great tutor I also need tutorial to customize comment form with out any plugin…

  8. Posted June 28, 2010 at 5:15 pm | Permalink

    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?

  9. Posted June 29, 2010 at 2:55 am | Permalink

    Awesome post dude I got a try it on my new upcoming web site.
    Thanks

  10. Ahmad
    Posted June 29, 2010 at 9:50 am | Permalink

    Hey, You have copied this stuff from this page:
    techtipsgeek.com/install-contact-page-in-wordpress-blog-without-plugin/6664/

    • Posted June 29, 2010 at 4:56 pm | Permalink

      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.

      • Ahmad
        Posted June 29, 2010 at 5:53 pm | Permalink

        Thanks for your clarification. I appreciate that you are bold enough to tolerate positive and negative criticism. Anyways good work.

  11. Posted June 30, 2010 at 5:50 pm | Permalink

    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.

  12. Posted July 1, 2010 at 3:37 am | Permalink

    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?

  13. radiact
    Posted July 1, 2010 at 6:45 am | Permalink

    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

  14. Posted July 2, 2010 at 5:29 am | Permalink

    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.

  15. HerrZ
    Posted July 2, 2010 at 11:32 am | Permalink

    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

  16. Posted July 2, 2010 at 11:48 am | Permalink

    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!

    • Posted July 2, 2010 at 12:37 pm | Permalink

      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.

  17. levar
    Posted July 7, 2010 at 12:06 pm | Permalink

    I keep getting an error at line 1

  18. Paranoid
    Posted July 8, 2010 at 6:23 am | Permalink

    Is this form secure from XSS and other stuff ?

  19. Posted July 9, 2010 at 2:08 pm | Permalink

    I am also using plug-in contact form but i was planning to change. Thanks for tutorial.

  20. Posted July 10, 2010 at 4:00 pm | Permalink

    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!

  21. Posted July 10, 2010 at 7:07 pm | Permalink

    Awesome! Tested, works fine.
    Thanks a lot for sharing. :-)

  22. Posted July 13, 2010 at 3:35 am | Permalink

    thanks the article!

  23. Posted July 13, 2010 at 4:02 am | Permalink

    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?

  24. Posted July 15, 2010 at 7:30 pm | Permalink

    Thanks, spent 5 or 6h on my form until I realized I could Google it :)

  25. Posted July 23, 2010 at 8:13 am | Permalink

    Thanks for posting this detailed and step-by-step tutorial. Tested it, it’s working fine.

  26. Bob
    Posted July 26, 2010 at 6:18 pm | Permalink

    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?

  27. Posted July 27, 2010 at 3:05 am | Permalink

    This was really a knowledgeable post…Expecting more posts like this.

  28. nackle
    Posted August 2, 2010 at 1:25 pm | Permalink

    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.

  29. Posted August 3, 2010 at 5:24 am | Permalink

    Nice post. I like to do all handmade

  30. carlos
    Posted August 4, 2010 at 8:33 am | Permalink

    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?

  31. Posted August 4, 2010 at 3:28 pm | Permalink

    Maybe you can help me out, how come the contact form will not work with the permalinks on? Is there a way around this?

  32. damien
    Posted August 9, 2010 at 7:36 am | Permalink

    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!!

  33. Posted August 9, 2010 at 8:10 am | Permalink

    Great stuff, nice to know this and how to do it will help wordpress bloggers everywhere.

  34. Posted August 10, 2010 at 4:26 am | Permalink

    I was also annoyed with the extra options and terrible code. So I will definitely use your code for my personal website

  35. Posted August 14, 2010 at 5:19 pm | Permalink

    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

  36. Posted August 18, 2010 at 6:30 am | Permalink

    Congratulations, good article!
    I think it is easier to use a plug-in, at least for me it is easier :-)

  37. Jake
    Posted August 19, 2010 at 2:38 am | Permalink

    Thank you for this wonderful tutorial!

  38. Posted August 21, 2010 at 5:56 am | Permalink

    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.

  39. Posted August 23, 2010 at 4:27 am | Permalink

    I have never like the generic forms that plug-ins offers.

  40. Posted August 25, 2010 at 2:01 am | Permalink

    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

  1. [...] 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 [...]

  2. [...] 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 [...]

  3. [...] How to create a built-in contact form for your WordPress theme Built-In Contact form for wordpress [...]

  4. [...] How to create a built-in contact form for your WordPress theme %CONTENT% [...]

  5. By Blog launch: 5 tips for success on July 12, 2010 at 9:40 am

    [...] 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 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Smashing Network
  • Hosted by VPS.net and Akamai CDN
WordPress Appliance - Powered by TurnKey Linux