How to create a built-in contact form for your WordPress theme

by Jean. 121 Comments -

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 (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", 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;

		wp_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 (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", 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;

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

  • http://annuaire.hdclic.com Djolhan

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

  • http://www.hiwaar.org/ hiwaarco

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

  • http://tipsforwordpress.com weston deboer

    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.

  • http://nyams.planbweb.com nyamsprod

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

    • http://boxmodeljunkie.com Nate

      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.

  • http://www.presscoders.com David Gwyer

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

  • http://knowledgecity.com Jae Xavier

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

  • http://www.technoweblog.com Mani

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

  • http://wpcanyon.com Boba

    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?

  • Pingback: How to create a built-in contact form for your WordPress theme « Wordpress Training

  • http://www.planetaston.com/ Vladan Krstic

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

  • Ahmad

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

    • http://www.wprecipes.com Jean-Baptiste Jung

      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

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

      • http://ubergeni.us Kevin Langley

        To be honest, there are a decent amount of bad coding practices within this site and even this blog post. As the other users have pointed out, I’m not sure why you’re still using eregi or why you’re writing a post about WordPress, but use mail() instead of wp_mail which then uses the PHPMailer class built within WP. Just saying.

        • http://www.wprecipes.com Jean-Baptiste Jung

          This post is 2 years old, it wasn’t that bad then. I have updated it.

      • Vibhor

        OK i made the contact form as you said. Pls let me know where to save this file and how to connect in my header or footer?
        Thank you

  • Pingback: 35+ Fresh WordPress Tutorials and Resources of June 2010 | DynamicWP

  • http://prop-14.com Randy

    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.

  • http://www.ajithprasad.com Ajith PrasadEdassery

    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?

  • radiact

    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

  • http://rssgreat.com James

    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.

  • HerrZ

    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

    • http://www.wprecipes.com Jean-Baptiste Jung

      You’re right, I should have used wp_mail(). Thanks for the notice.

    • ESTEBAN

      I agree, using wp_mail() is a better option.

  • http://legendscrazy.net/ Dale

    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!

    • http://www.wprecipes.com Jean-Baptiste Jung

      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.

  • Pingback: F.I.A.T – June 2010 » Ephan Design | Blog and Portfolio of Web and Graphic Designer Ben Stephan

  • Pingback: Here’s What We’re Reading – July 7, 2010 :: Warbux Creative

  • levar

    I keep getting an error at line 1

  • Paranoid

    Is this form secure from XSS and other stuff ?

  • http://1stblogger.com/ Rakesh Solanki

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

  • http://www.antoineguedes.com Antoine Guédès

    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!

  • http://www.twitter.com/mamunabms Abdullah Al Mamun

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

  • Pingback: Blog launch: 5 tips for success

  • http://www.acily.com Aci

    thanks the article!

  • http://www.directcustomgolfclubs.co.uk/ Brian

    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?

  • http://1337poker.com Benny

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

  • http://www.youtube.com/watch?v=uEr-DG7g__8 Jamie

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

  • Bob

    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?

  • http://www.zervidesk.com/ Dave George

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

  • nackle

    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.

  • http://www.diseñadorwebmurcia.com Javier Murcia

    Nice post. I like to do all handmade

  • carlos

    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?

  • http://www.vrmetro.com Steve Markey

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

  • damien

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

  • http://www.audiovisualgifts.co.uk Douglas Isaac

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

  • http://www.inikeairjordan.com vansci123

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

  • http://lesleyklatt.com/ Lesley “Wes” Klatt

    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

  • http://www.kuandika.com Simone

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

  • Jake

    Thank you for this wonderful tutorial!

  • http://www.writeyourbookmasterclass.com Tiffany

    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.

  • http://www.inikeairjordan.com vansci123

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

  • http://sue-mcdonald.com Sue McDonald

    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.

  • s0s0

    This is a great tutorial, thank you so much for sharing. As many others have said, it’s better than a plugin and great when you need a little bit more flexibility in your forms.

    Just a quick question: is it possible to break up a really long form with maybe a ‘next button’ or something to move onto the next section?

    I have a really long form I am creating with about 5 different sections but I’m a bit concerned about the length of the page as it;s going to be huge!

    If anyone has any idea’s how I could get around this issue, I would greatly appreciate it.

    Thanks

  • http://todayblogtips.com Le Hoang

    Thank you for this tutorial!

  • http://www.flotrolreview.org Daniel

    I do think it’s very important to have a contact page and this was a perfect tutorial. Really helped me out.

  • http://www.extension103.com Extension:103

    hey, i love this article and i am including it in my latest theme.

    only problem is i get errors with wp debug set to true.

    Undefined variable: nameError
    Undefined variable: emailError
    Undefined variable: commentError

    chedck through all code and cant find the issue (i can see where the error is but dont know how to fix it.)

    any help would be great.

    • http://na peter

      yes, you see this because you correctly have DEBUG turned on.
      put this at the top of code:

      //initialize vars so dont thow errors on 1st time
      $nameError = ”;
      $emailError = ”;
      $commentError = ”;

  • http://redheaddesign.net Jen

    Love the idea of this, just hate that it doesn’t utilize any anti-spam methods. Not complaining though. :)

  • Dries

    Great tutorial! I love how this works!

    But I do have 1 problem tho, I can’t seem to get the validation working….

    Could you please explain how to install the jquery in detail? I read the provided steps carefully, but it doens’t seem to work.

  • http://www.redkitecreative.com/ Debbie

    This is a great tutorial, it’s working perfectly.

    I have a contact form on each car post page for a car dealer site. How do I get the name of a car (title of the post) entered as a hidden field so that when the site owner receives it, he knows which post it came from?

  • Matti

    I was wondering whether a captcha style image verification could be added to this contact form in order to cut down on the spam/junk mail I am receiving, do you think this is possible? I have seen a number of simple jquery based methods of checking forms for human verification – could these methods be built in?

  • Guest

    Great tutorial! Someone mentioned that eregi should be replaced with preg_match, but you have to modify the expression. There is also a built-in php filter FILTER_VALIDATE_EMAIL.

    Bob writes that the emails are labeled as coming from him. I think $emailTo in $headers should be just $email.

    Also, a simple human check would be nice, e.g. add two random numbers.

  • http://thehillsarborists.com.au/ Joseph Gray

    Captcha can be added this it seems. But there are many things which can be validated without captcha also.

  • http://snipedia.net Emilio V.

    This form works as a wonder to me, but I have a question: what do I need to modify in order to make it work inline in a post? That is, as a particular template but elsewhere; on a front page, for example. Been killing myself with the question for a while.

  • http://funwidmasti.com/ siddharth Sharma

    I liked this idea
    Nice work..!!:)

  • Colin Donaghey

    Is it possible to have the code for the form in an actual post rather than the template?

    Brilliant post by the way. Keep it up

  • skinnyboy

    another tut bookmarked! i should be starting implementing soon
    anyway,
    i have been trying to figure out how to have the form not being self referencing, i prefer having a separate form handling script and do all my stuff in there, but i can’t figure out where to place it,
    any hints would be appreciated
    thank you in advance

  • Mark

    Hello!!

    First of all thanks for the awesome tutorial. i went from basically no PHP and jQuery experience to creating a custom form.. bad ass. thanks for that :)

    So now onto my question: How do I customize the look of these boxes?

    I already adjusted the rows and columns in the “message” section, and I wanted to know how I can get all of the fields to line up evenly???

    Also, the word “Message” appears towards the bottom of the message field.

    Is the lining up evenly and “message” at the bottom of the field a CSS thing? If someone can just get me going in the right direction im sure i can figure it out, just need a little nudge.

    Any help is appreciated.

    Thanks again.

    Since the

    • http://emiliovelis.com Emilio Velis

      Yes! To get you in the right direction on the CSS, you can first try the ‘width’ of each box and then the ‘float’ selector for each div. I haven’t played with the CSS of this form in a while but it could be something like this:

      #entry-content {
      width:###px;
      }

      .contactform li{
      width:###px;
      float:left;
      }

      Let me know if you have any questions..

      • http://DUMBY805 Mark

        Thanks Emilio!!

      • Kat

        I am having the same problem as Mark :( sorry I am new to this. Where would I add the CSS for the above? within the CSS Style Sheet or within the Content Page itself (.php)?

        Thank you!

  • Dariusz

    Hi, I’m working on a wordpress web site where there will be 5 users (4 admins a fake editor with the name lets say editorial office). How can I change the e-mails to go to the fake editor (because thats the e-mail we all have access) ?

    its in this code: if(!isset($hasError)) { $emailTo = t_option(‘tz_email’);
    if (!isset($emailTo) || ($emailTo == ”) ){ $emailTo = get_option(‘admin_email’);

    but I don’t know how to change it

  • Chua Wen Ching

    Hi, I got an error

    Parse error: syntax error, unexpected ‘{‘ in /wp-content/themes/theme1161/page-contact.php on line 1

    I am not sure what’s wrong.

    If I remove the codes between the header template and get_content, then this error will disappear.

    – PHP Template –
    (remove php validation logic here)
    – PHP Get_Header() –

    Do I need to install any plugin or something to get this to work?

    If I replace the php validation logic to something simpler like print hellow world, then i got a new error

    Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

    Any help? Thanks.

  • Michał

    There’s a typo in “A buil-in WordPress form was initially created[...]” – should be “A BUILT-in[...]“(you misspelled the “built-in” word). It doesn’t actually matter, but I decided to let you know. The article itself was really helpful for me, tho.

  • Paul Hinds

    Hi i was wondering if you had a tut explaining how to style this scripts with css, and if so could you send me a link?

  • http://catalystwebexperts.com jitesh

    Great tutorial….can you please tell me how can i store values in db and then show to my wp-admin………
    thanks in advance :) …waiting for your reply…

  • http://webestatesinc.com Lev

    Nice work but your jquery validation script is malfunctioning it gives me the following message after the submit button “You forgot to enter your .You forgot to enter your .You forgot to enter your .” something wrong with getting the input label id, value.

    Cheers!

  • Rehan

    how can i access this page contact.php ?

  • stan

    hi, great tutorial. Just one question– do we really need the jquerry plugin or can the form work without it?

  • Luchman

    How do you link to the contact page..what’s url like?

  • Steve

    This tutorial is nothing more than how to create a custom template page with a form in it. It isn’t really built in. How about adding Admin menu panels and being able to edit and customize the form from the backend? Now that is what I would call “built in”. Or am I wrong?

  • http://www.forthosewhowait.com Gregory G. Armento

    replace eregi function with preg_match [code]
    else if (!preg_match("/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i",
    trim($_POST['email']))) { [code]

  • http://www.forthosewhowait.com Gregory G. Armento

    us wp_mail instead of mail
    [code] wp_mail($emailTo, $subject, $body, $headers);
    $emailSent = true; [code]

  • http://www.forthosewhowait.com Gregory G. Armento

    multiple email recipents…
    [code]
    if(!isset($hasError)) {
    $emailTo = get_option('tz_email');
    if (!isset($emailTo) || ($emailTo == '') ){
    $emailTo = 'email1@example.com';
    }

    $subject = 'Website Contact, from '.$name;
    $body = "Name: $name \n\nEmail: $email \n\nPhone: $phone \n\nComments: $comments";
    $headers = 'From: '.$name.' ' . "\r\n" . 'Reply-To: ' . $email;
    $headers .= 'Bcc: email2@example.com' . "\r\n";
    $headers .= 'Bcc: email3@example.com' . "\r\n";
    [/code]

  • http://www.theagence.fr Nicolas

    Wow, very extensive. Thanks for that. I will use that in my WordPress templates!

  • Brian

    Thank you so much for the excellent tutorial!

    For the website I’m working on, I’m hoping to have two separate contact forms that will go to two separate email addresses. How would I implement this? Thank you!

  • http://www.reflexzion.com/ Julio

    Thanx much for this tut! I hope you’re still offering support because I have one question. How can I change the “default” admin_email to a custom email address or perhaps even include an option when choosing the page template in the back end to specify an email?

    • http://www.reflexzion.com/ Julio

      Got it! It wasn’t the code at all…

      • Ornis

        Can you please help me where do I change that admin_email? I am trying to get emails but not success. Not sure what exactly do I need to change! I am so new at this! Thanks in advance!!!

        • http://www.wprecipes.com Jean-Baptiste Jung

          you should replace
          $emailTo = get_option(‘admin_email’);

          by

          $emailTo = ‘you@gmail.com’;

  • Alvaro

    Great tutorial. Just one thing. As you gave a special template page for this (contact.php), I think it would be better to make the if statement in the header like this:

    if ( is_page_template(‘contact.php’) )

    Thanks!

  • neomale

    Hi, great tutorial, but i have one problem it doesn’t work, for me. I explain i add all your code in the template. I see the form and i fill all the fields and click on send. I got the message “Thanks, your email was sent successfully”. But i don’t receive any email at all??? I check my spam nothing, also check the assassin spam in my cpanel nothing i made many test but i got nothing. It tell me no error. I have WP 3.2.1. Any idea of what is going wrong???

    Regards

    • http://www.amandahwood.com Amanda

      I’m having the exact same problem, did you have any luck figuring it out??

    • komiska

      Me too! Anyone a hint where the problem is? ;(

    • komiska

      All right, girls! In my case , which got happily resolved today, the problem was the missing standard e-mail on the hosting provider side. This in itself is weird, because usually this is standard setting, but in my case , obviously not. I suggest you talk to your providers as well, maybe the solution will be the same?

      And thanks again to Jean-Baptiste, who has written such a great and educational code example!

      Cheers!

  • http://gavsiu.com gavsiu

    Just sharing some thoughts…. I replaced the preg_match with the is_email function from WordPress for simplicity of the script and to keep email validation the same throughout my WordPress (also for post comments).

  • http://www.iBatesDesigns.com Ian

    What about the all new fancy WP Contact form via WordPress 3.3 Jetpack?
    http://en.support.wordpress.com/contact-form/

    It has Akismet filtering, and now archives all contact form requests just like posts. I’m in the process of converting my blogs to this format. Anyone can now build forms. No HTML Knowledge required. It’s just like MailChimp’s form builder. Intuitive and quick.

    I know the article is almost 2 years old, just thought I’d share in case anyone hasn’t seen it. I highly recommend Jetpack. They send you cool stats email too each year.

  • Ornis

    I know that this might be the dummest question ever, but what part should I edit to get emails.
    I edit mine like this but not success. Please HELP!!!
    if(!isset($hasError)) {
    $emailTo = get_option(‘ornis@gmail.com’);
    if (!isset($emailTo) || ($emailTo == ”) ){
    $emailTo = get_option(‘ornis@gmail.com’);
    }
    $subject = ‘[PHP Snippets] From ‘.$name;
    $body = “Name: $name \n\nEmail: $email \n\nComments: $comments”;
    $headers = ‘From: ‘.$name.’ ‘ . “\r\n” . ‘Reply-To: ‘ . $email;

    wp_mail($emailTo, $subject, $body, $headers);
    $emailSent = true;
    }

  • http://www.cross-town-traffic-software.com Toren

    Thanks, one problem is the as is form deletes the button, so I end up with submit query label in my button.

  • Frank

    Very very nice! Fits perfect to my needs and stops me from sticking with flawing plugins all the time! Thank you very much!

    There’s one suggestion I would like to make: In the class-attributes of the required fields you currently set “required requiredField”. I think only the latter of those strings is required to perform the jQuery validation while the first actually calls the WP core class for the asterisk character in comment fields. As this displays the entered text in bold red I would simply strip off the first “required”.

  • http://www.amandahwood.com Amanda

    Can anyone help me? I’ve copied and pasted the exact code into a contactform.php file and it’s saying the email has sent successfully but I don’t receive the email. I’m currently building the form locally so could that be why?

    • http://www.fourleafed.com FourLeafed

      If you are building your form locally you need to make sure the mailserver is running/ configured properly. Otherwise no mail will be sent.

      E

    • komiska

      I have put this live and it’s still not sending any mails. there must be some flaw in the script :/

      • http://www.desitechboard.com parax

        Check your mail server is running and can send mail.

  • rebecca

    Everything about this has worked beautifully for me… with the exception of receiving the emails.

    I made some changes to the code for the actual contact form (hence the different IDs etc.) But I haven’t changed anything that would affect the functionality of the email delivery.
    [code]
    if(!isset($hasError)) {
    $emailTo = get_option('tz_email');
    if (!isset($emailTo) || ($emailTo == '') ){
    $emailTo = get_option('admin_email');
    }
    $subject = '[NEW- Online General Inquire] From '.$first_name;
    $body = "First Name: $first_name \n\nLast Name: $last_name \n\nEmail: $email \n\nPhone: $telephone \n\nCompany/Organization: $company \n\nRole/Title: $title \n\nMessage: $message";
    $headers = 'From: '.$first_name.' ' . "\r\n" . 'Reply-To: ' . $email;

    wp_mail($emailTo, $subject, $body, $headers);
    $emailSent = true;
    }
    [/code]

    Help!

    Also, awesome “how-to”!

  • gregorio

    hi!

    thanx really like your programming

    anyway how would you add a file uploader, so that people can send pix or documents to the email??
    ^^

  • http://emwhytee.wordpress.com Yousuf Tafhim

    Nice tutorial, it works smoothly.
    By the way does the spam plug-ins work fine with it?

  • Michael

    Thanks – great tutorial!
    How do you implement this in the sidebar using PHP? (Using twenty-eleven) I have a quick-info form that I created for use in the sidebar of several pages. When I add the html in the sidebar widget template’s text code box it does not seem to permit the use of PHP, as the value=”” code appears within the input fields. I have modified the code as standard html form code and added the PHP variable conversion to the page.php header, but this does seem to work. For the moment, I would like to solve this with PHP and then later possibly implement the jQuery option. Do I place all of the code within the sidebar template?

    Also, as a separate note, some hosting mail servers do not accept the wp_mail($emailTo, $subject, $body, $headers); and require just “mail” instead of “wp_mail”

  • Flatland

    Total beginner’s question here:

    How does the form know what email address to send to? How would one edit this?

  • http://disennio.com Alvaro

    If you need captcha support you can use this script:
    http://www.white-hat-web-design.co.uk/blog/php-captcha-security-images/

    and add this to your php code:

    session_start();
    if(($_SESSION['6_letters_code'] == $_POST['6_letters_code']) && (!empty($_SESSION['6_letters_code'])) ) {
    $captcha = trim($_POST['6_letters_code']);
    unset($_SESSION['6_letters_code']);
    } else {
    $captchaError = ‘Por favor escriba el código captcha.’;
    $hasError = true;
    }

    And this to the html:
    <img src="/path/to/captcha_code_file.php” alt=”captcha” />

  • http://www.gourmetdesign.com.au Damien

    Thanks for the tutorial.

    Who does it notify when the form is submitted, and where in the code can you set this?

    I want to use this on a multisite network and have it part of the template site, so that it emails the form to the site admin (of the subdomain) automatically.

  • Al

    How do you save that data submitted? I assume is the code in the_permalink() procedure?.

    and it would be just plain php on the server?

  • Andrei

    What does this mean?
    get_option(‘tz_email’);
    tz_email?

  • Alex

    Gettin errors :(
    Notice: Undefined variable: nameError and the rest Error variables… I’ve made them global.. It works now, but Iam not sure if it is right..
    I am quite new to this.. Can you suggest me and direct me into right direction?
    Thanks in advance

  • sam

    Great tutorial but I can’t figure out how to connect the jquery plugin. My form is using bootstra and I followed the tutorial and created the verif.jf file with the following code:
    jQuery(document).ready(function(){
    jQuery(“#contactForm”).validate();
    });
    but it won’t do anything, I get confused about what name should the fields have in order to get triggered by jquery when they are no valid or empty. If somebody has a suggestion would be great.
    Thanks

  • http://meldville.com ket

    It isn’t work for my theme. It redirects to 404 error but the URL remains unchanged. What possibly went wrong with my setting?

  • natehawkes

    This looks great! How friendly is it, however, with plugins like Akismet?

    • http://interiii.com cleo lego

      I think sometimes is better to use a free online form builder like formaya.com or any other, because your forms are embed and you don’t have to install plugins all the time, causing page weight load and code conflicts. any way this tutorial is awesome

  • Arpita Patel

    Hello,

    When i use this code and when trying to send mail at that time page will be submitted and page wiil be blank at that time.
    so what can I do???
    please give me any solution…

    Lots of Thank you…