There are lots of WordPress plugins for contact forms, 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.
Some people may want to skip the post and get to the demo and source files:
View Demo Download Source Files
So, why not use a plugin?
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.
The Plan
Our plan is to create a custom WordPress Page Template, then create a page that uses that template. Finally, we will add in a little jQuery to improve the form. Let’s write a little pseudo code to help determine how our page template will be structured.
Pseudo Code
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)
Creating the WordPress Page Template
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.
<?php
/*
Template Name: Contact Form
*/
?>
<?php
//If the form is submitted
if(isset($_POST['submitted'])) {
//If there is no error, send the email
if(!isset($hasError)) {
}
} ?>
<?php get_header(); ?>
<?php
//If the email was sent, show a thank you message
//Otherwise show form
if(isset($emailSent) && $emailSent == true) {
?>
<?php } else { ?>
<?php } ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
The Form
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:
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<h1>Thanks, <?=$name;?></h1>
<p>Your email was successfully sent. I will be in touch soon.</p>
</div>
<?php } else { ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">
There was an error submitting the form.
<p>
<?php } ?>
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
</form>
<?php endwhile; ?>
<?php endif; ?>
< } ?>
If the emailSent 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:
<ol class="forms">
<li>
<label for="contactName">Name</label>
<input type="text" name="contactName" id="contactName" value="
<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>"
class="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="requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li class="textarea">
<label for="commentsText">Comments</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="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 class="inline">
<input type="checkbox" name="sendCopy" id="sendCopy" value="true"
<?php if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true)
echo ' checked="checked"'; ?>
/>
<label for="sendCopy">Send a copy of this email to yourself</label>
</li>
<li class="screenReader">
<label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field</label>
<input type="text" name="checking" id="checking" class="screenReader" value="
<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>"
/>
</li>
<li class="buttons">
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit">Email me »</button>
</li>
</ol>
Note: Line wrapping added for readability.
Ok, wow, that may seem like a lot. So let’s break down the name field to see what this code is actually doing:
<li><label for="contactName">Name</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
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.
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.
We are also using honeypot captcha to see if a bot was trying to submit the form:
<li class="screenReader">
<label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field</label>
<input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>" />
</li>
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:
.screenReader {
left: -9999px;
position: absolute;
top: -9999px;
}
The Validation
Next, we are going to have a conditional statement to determine if the form was submitted or not:
<?php
//If the form is submitted
if(isset($_POST['submitted'])) {
} ?>
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:
//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
} else {
}
So if the captcha field was left blank, we will continue to validate the required fields:
//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']);
}
}
Again, that may seem like a little much, so let’s just take a look at the validation on the name field:
if(trim($_POST['contactName']) === '') {
$nameError = 'You forgot to enter your name.';
$hasError = true;
} else {
$name = trim($_POST['contactName']);
}
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.
Sending the Email
Now, we want to send the email if there are no errors:
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = '<strong>me@somedomain.com</strong>';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name nnEmail: $email nnComments: $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "rn" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
if($sendCopy == true) {
$subject = 'You emailed <strong>Your Name</strong>';
$headers = 'From: <strong>Your Name</strong> <<strong>noreply@somedomain.com</strong>>';
mail($email, $subject, $body, $headers);
}
$emailSent = true;
}
Note: Items bolded are values that you will want to change before implementing.
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.
View Entire Custom Page Template
Creating the Page in WordPress
First, you want to upload the contact-form.php page template to your themes folder. Next, you will create the page in WordPress and select Contact Form as the page template.

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.
Styling the Form
I recently wrote an article about styling forms, so we are just going to stick with some basic styles:
.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; }
So drop that CSS in your theme stylesheet and you will see the form start to look much better.
Enhancing the form with some jQuery
I have also already written about creating AJAX forms with jQuery, but I thought I would specifically talk about an AJAX script for a contact form.
First, we want to execute our jQuery when the document is ready and the form was submitted:
$(document).ready(function() {
$('form#contactForm').submit(function() {
return false;
});
});
Next, we want to hide any error messages if there are any and validate any required fields which are denoted with a class of requiredField:
$('form#contactForm .error').remove();
var hasError = false;
$('.requiredField').each(function() {
});
After that, we want to validate that the field is not empty and append an error message if it is:
if(jQuery.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
hasError = true;
}
If the field is not empty and also has a class of email, we want to validate that the email address is valid:
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('<span class="error">You entered an invalid '+labelText+'.</span>');
hasError = true;
}
}
If there are no errors, then we want to replace the submit button with a loading image:
if(!hasError) {
$('form#contactForm li.buttons button').fadeOut('normal', function() {
$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});
Note: You will need to update the source of the image to wherever you upload it in your theme.
Finally, let’s submit the form via an AJAX request, slide the form up, and show a thank you message:
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contactForm').slideUp("fast", function() {
$(this).before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.</p>');
});
});
Take a look at the entire script:
$(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('<span class="error">You forgot to enter your '+labelText+'.</span>');
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('<span class="error">You entered an invalid '+labelText+'.</span>');
hasError = true;
}
}
});
if(!hasError) {
$('form#contactForm li.buttons button').fadeOut('normal', function() {
$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'),formInput, function(data){
$('form#contactForm').slideUp("fast", function() {
$(this).before('<p class="thanks"><strong>Thanks!</strong> Your email was successfully sent. I check my email all the time, so I should be in touch soon.</p>');
});
});
}
return false;
});
});
Just include it in the head of your document after jQuery, and you are good to go:
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/jquery.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/scripts/contact-form.js"></script>
Note: You may need to change the source depending upon where you upload the files in your theme.
Conclusion
View Demo Download Source Files
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!
243 Comments
Buzzlair Voufincci
02.26.2009mate! thanks for this. been looking for this for months. helpful.
ps : i dont like to use plugins. writing own codes is better “understanding self-coded code is a satisfaction”
James Coletti
02.26.2009I don’t get why you aren’t using a plugin and embedding the contact form functionality directly into the page template? Doesn’t that defeat the purpose and flexibility of plugins? If you change your theme, you have to port over your page template to your new theme. If you develop it as a plugin, it will inject any contact form markup you want into the page dynamically and all you’d have to do is style it differently with CSS. You can also add configuration options to your form via the plugin API. If you implement it using shortcodes, you’d just stick something like “[contactform]” into your page content and the form would render there. I found a lot of overly-bloated contact form plugins out there… which is why I created my own, too ;)
http://jamescoletti.com/simple-wordpress-contact-form-plugin
Trevor
02.26.2009@James-
The reason I didn’t do it as a plugin is because I don’t have that kind of time to add in all the bells and whistles with an admin interface and provide support for the plugin.
The idea is that you just have the code. It’s easy for a savvy user to update the form for themselves.
Personally, I like having the actual code to edit instead of passing it into this “black box” and seeing what the plugin produces. I like to have control over every piece of code I can on my site. Maybe not everyone is as anal as me though…
timtipper
03.02.2009Sure, it looks great. When I apply the CSS to my stylesheet, it moves the “email yourself” check box wayyyyy over to the right.
Also, what does it actually do with the comments entered? When I test it out, it doesn’t show the comments in any folder.
Trevor
03.02.2009@timtipper-
Do you have a link to the page? I could have easily missed some styles when pulling it into a separate stylesheet or something in your stylesheet could be overriding it.
yoosuf
03.05.2009its awesome!
Olli
03.08.2009Very nice script, works like a charm. Just a question concerning the style of the error output: Would it be possible to give every input field with a missing/wrong input text a red border instead of display an error-message on the right of the input field via span?
Trevor
03.09.2009@Olli-
Sure, you will just want to change this code:
if(jQuery.trim($(this).val()) == '') {var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
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('<span class="error">You entered an invalid '+labelText+'.</span>');
hasError = true;
}
}
To this:
if(jQuery.trim($(this).val()) == '') {var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You forgot to enter your '+labelText+'.</span>');
<strong>$(this).addClass('inputError');</strong>
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('<span class="error">You entered an invalid '+labelText+'.</span>');
<strong>$(this).addClass('inputError');</strong>
hasError = true;
}
}
That should add the class of inputError to the form elements. Then, you can style them accordingly.
Olli
03.10.2009@Trevor-
Thx for your fast reply. Unfortunately it seems I’m incapable to change the CSS the right way. I changed the JS as you told me and added the following to my CSS:
#contactForm ol.forms .inputerror {border: 1px solid #0000FF;
}
But the only error message visible is still the red span-text on the right of the input-fields; there is no border around them. Do you have any idea?
Thx in advcance!
Trevor
03.10.2009@Olli-
Don’t forget that class names are case sensitive. In the JS, I told you to put inputError, but in the CSS you showed, you put inputerror.
Olli
03.10.2009@Trevor-
Damn, of course I forgot - now it works. Thank you very much :)
Andrei Gonzales
03.14.2009While I agree with you regarding your reasons why you didn’t use a plugin (I don’t either - too much overhead when different clients, more often than not, require different contact forms). However, I wonder why you didn’t use jQuery’s Validate plugin for validation?
Trevor
03.15.2009@Andrei Gonzales-
I don’t use a jQuery plugin for the same reason I wouldn’t use a WordPress plugin: the plugin adds extra bloat when I don’t really need it, and I want to have completely control over the code.
Especially when it is something so easy as form validation, why not just do it yourself?
RaiulBaztepo
03.28.2009Hello!
Very Interesting post! Thank you for such interesting resource!
PS: Sorry for my bad english, I’v just started to learn this language ;)
See you!
Your, Raiul Baztepo
Raymond Selda
04.04.2009Good thing I bookmarked this article! This tutorial was a big help in rolling out my own contact form that I’m using in my blog.
Thank you Trevor!
Montana Flynn
04.05.2009Wow, that was a great tutorial! Thanks I used it on my blog’s contact page!
jitendra
04.20.2009After setting up this form i didn’t get any mail in my inbox.
jitendra
04.20.2009I want to use my free gmail account to receive mail through contact us fom
Trevor
04.20.2009@jitendra-
You are going to have to provide more information. Are you receiving any errors? Do you have a url to the page? Is it getting caught in your spam filters?
bitka
05.09.2009Great tutorial, thanks Trevor. I also like to see what’s happening on the page and have full control so this is the perfect solution.
I have one problem I was hoping you could shed light on - the form isn’t sliding up at the end. ie .slideUp isn’t firing in the jquery which is odd because the callback function adding the ‘thanks’ paragraph in before it is working! I’m using the latest jquery release 1.3.2 instead of the one packaged with your files but I don’t think that would affect this. Any ideas you have would be greatly appreciated. Thanks :)
Trevor
05.10.2009@bitka-
Did you have a link so that we can see the error?
Maria Mingosmo
05.12.2009Hi trevor
I’ve already used the other form mailer you created in this website. With a few changes and it works like a charm. Sorry but I had to ditch the ajax stuff.
Now about this one (that’s for a wordpress project), will it work with a custom thank you page (because of conversion tracking)?
I think that instead of showing some code after the form is submited, we can do a redirect to the thank you page, am I right? And will this enable me to put contact records in a database without any wordpress conflits?
Sorry if I ask to much.
Thanks in advance Trevor
Maria M.
Trevor
05.12.2009@Maria Mingosmo-
You could always just add a parameter in the URL so that it would track the conversion.
So instead of /contact/, try /contact/?thanks
If that isn’t enough for you, then you could do a redirect before any headers are sent.
Maria Mingosmo
05.13.2009I really need a separate Thank you page (really need google conversion tracking on that one), so i’ll try to redirect users after all the form fields are validated. I will let you know how it worked out.
Thanks for your kind reply. Keep on coding, I’m lovin it! ;)
Cheers
Maria M.
future
05.13.2009Great work! But how about spam? Many contect form plugins have anti-spam sistem
Trevor
05.13.2009@future-
The form is already using honeypot captcha, and you could easily add in another method.
stu
05.14.2009Hi Trevor,
After going thru so many contact form plugins I came accross your tutorial and I chose to implement your contact form. What a surprise! :).
Thank you very much for sharing your work. However, I have one question. How to make the form slide up. It doesn’t do it. However, the console with firebug shows the correct response but no refreshing of the page. What did I do wrong?
Thank you,
Stu
P.S. my site is wordpress.stumillersmovers.com
Trevor
05.14.2009@stu-
You know, that’s weird, bitka was having the same problem. I don’t see anything in the code that would cause a problem.
Maybe try only using the $(’#contactForm’) selector. Maybe try switching your doctype to be strict (that’s the only real difference I see between my example).
stu
05.14.2009@Trevor-
Thank you for your suggestions, but still no sliding up and I realized that even your demo is not sliding up…?
How to simply modify your code to just refresh the form?
Trevor
05.14.2009@stu-
Weird, it was definitely sliding up before. So when you say refreshing the form, you just want to remove the values from the field? Just try setting the value attribute to nothing, that should do it.
stu
05.15.2009@Trevor-
This is how I fixed it:
if(!hasError) {
$(‘form#contactForm li.buttons button’).fadeOut(‘normal’, function() {
$(this).parent().append(’‘);
});
var formInput = $(this).serialize();
$.post($(this).attr(‘action’),formInput, function(data){
$(“form#contactForm”).before(’Thanks! Your email was successfully sent. I check my email all the time, so I should be in touch soon.’);
});
$(“form#contactForm”).slideUp(“slow”,function() {});
}
and it works like a charm. Thank you!
stu
05.15.2009I forgot to mention that there needs to be a in the to be able to slide. If there is no div, no sliding…
stu
05.16.2009I meant a tags in the tags and it works great…Go figure :)
stu
05.18.2009Still missed it! I spent too much time in front of a computer…. I meant div tags. There need a tag and it works great.
Guresh
06.27.2009It would be good if add spam prevention feature.
Trevor
06.27.2009@Guresh-
There is already honeypot captcha added to the form. You could easily add in something else as well.
akber kabir
07.02.2009Hi, thanks a lot for such a beautiful tutorial, i have a question,
could you please show me how can i add a text field that will validate an URL?
thanks
Trevor
07.02.2009@akber kabir-
You will want to validate the field similarly to how the email address is validated, you will just need to use a URL regular expression.
kristian
07.11.2009Trevor,
I’ve gotten your code to work just fine when on a page.
However, I’m attempting to stick this in my index.php file… and obviously its not working because there is an issue with the url of the form action.
what do you suggest i use for that form action url?
On click it says “thanks” etc etc, but its really not working because it wont send. (but it does send when in a page)
Trevor
07.13.2009@kristian-
The way that I have coded the form, you should always have the form action be the current page that it is on.
So if you have added the form onto the index.php file, then you want the form action to be index.php.
Larry
07.20.2009Thank you so much for your hard work and the great contact form. I am currently using it on an upcoming project and was wondering if you could help me implement a drop-down option menu? The user selects a subject for the inquiry and this selection determines which email address the message gets sent to.
Trevor
07.20.2009@Larry-
Sure you could easily add in a select element that adjusted the subject of the email. Just add in the HTML and adjust the PHP to accommodate the new field.
Larry
07.20.2009Ok, after a little research this is the basic code I’ve come up with. This is the first time I’ve tried to do this and my PHP knowledge is very basic, so please bare with me.
HTML for form:
GeneralBooking
Press
PHP to process form:
switch($_POST['subject']){case 'general':
$emailto = 'info@example.com';
break;
case 'booking':
$emailto = 'booking@example.com';
break;
case 'press':
$emailto = 'press@example.com';
break;
}
Does this make sense?
Trevor
07.20.2009@Larry-
Makes sense to me
Larry
07.20.2009@Trevor-
I’m not sure why the HTML wouldn’t post. I wrapped it in the proper tags.
Trevor
07.20.2009@Larry-
Like pretty much all blogs, you must encode the open bracket < to be <
Barton
07.22.2009Great article, and even contains validation ;-)
The only problem is that I want the error messages to appear underneath the relevant inputs. With the appends used, is this possible?
Thanks.
Trevor
07.22.2009@Barton-
Absolutely. If you modify the css for the error class, you can get them to display however you want.
Deborah
08.08.2009Thank you for writing this post about creating your own contact form, without having to use a plugin.
Question for you: I have a site that requires more than 1 contact form, with different fields on each form.
Are there any options you recommend for implementing your template for use in multiple forms on a site?
Trevor
08.08.2009@Deborah-
Sure, just create multiple page templates. Then select the appropriate template for each page with the form on it.
kucrut
08.09.2009thank.you!!!
Rhys
08.12.2009Awesome template, it was exactly what I was looking for, I also dislike using plugins as well.
BTW, you don’t have a closing tag in the “View Entire Custom Template” link in your tutorial found at:
There was an error submitting the form.
Thanks!
Edit: Spaces added.
Trevor
08.12.2009@Rhys-
I’m not sure what you mean. I don’t see where there is a missing closing tag.
Nort
08.25.2009I created an e-mail field in the theme panel, but the contact form won’t recognize the field.
Does the form accept the options call in the e-mail field ? i.e. if I place instead of the e-mail address :
It is not working and I have already inserted the code to enable the option in the contact page template.
Any help will be appriciated
Trevor
08.25.2009@Nort-
I’m not sure what you mean. Can you explain in more detail?
Nort
08.25.2009sorry code didn’t show :
Nort
08.25.2009thanks for fast reply. For example, you have to change the e-mail address where you want the form to send the e-mail in the contact-form.php file.
Instead I created a custom field in the theme options panel, so that my client can change the contact e-mail whenever he wants without touching code.
However, the form does not understand that field, even though I think I have inserted the code correctly, and I am calling the theme options in the contact page template….
Trevor
08.25.2009@Nort-
So are you accessing the option using get_option? It seems like that should work fine.
Nort
08.25.2009yes, I am accessing the option and everything, normally I know how to do it. The form works fine if the e-mail is inserted directly.
I have no idea why that’s happening, maybe because of the script ?
Trevor
08.25.2009@Nort-
So if you just output the option on the page it works fine? Without seeing any code, I can’t give you any reason why it wouldn’t work.
Lee Floyd
08.27.2009Your code helped me understand how to adapt my current contact form into a Wordpress page. I had everything right except for the permalink code in the action and the way you persisted the values.
Andrew
09.02.2009Hi,
What a wonderful tutorial. It is great.
However, I am curious where you put the conditional code in your real demo?
You guide the audience as shown in your contact-form.php, that the following will be included:
//If the form is submitted
if(isset($_POST[‘submitted’])) {
But when I see your demo page and display your source code, you just start from the following:
<form action="
Can you explain the difference between what is in your guidance and your own usage?
Also (another question), if you have :
If have post, while have post, the-post,
After click the SUBMIT button, it will display a post, instead of the message (either the red error message or thank you message), as shown in your tutorial.
How to solve these problem?
Thank you Trev!
Trevor
09.02.2009@Andrew-
I’m not sure what you are asking. If you look at the PHP file that you can download, you will see where that code is.
Do you have a link to see the problem you are having?
Andrew
09.02.2009Thanx for quick response, and sorry for the 2 questions as I found the answers already.
I realized that HTML does not display some PHP codes. Also I modified the url of the js files, now they works.
But the $emailTo = ‘me@somedomain.com’; doesnt work. Yes of course I have replaced it with my own email address, but still doesnt work as I never receive email after click the EMAIL ME button. Can you explain why? Bytheway, I dont have link, I just do experment locally with wamp.
And also (another question), at this part:
if($sendCopy == true) {$subject = ‘You emailed Your Name’;
$headers = ‘From: Your Name ‘;
mail($email, $subject, $body, $headers);
Should I replace .(JavaScript must be enabled to view this email address) with my email? Please kindly clarify.
Thanks once more, Trev
Andrew
09.02.2009if($sendCopy == true) { $subject = ‘You emailed Your Name’; $headers = ‘From: Your Name ‘; mail($email, $subject, $body, $headers);
Trevor
09.02.2009@Andrew-
Are you sure you have mail to work setup locally?
Unless you want it to come through in the email as .(JavaScript must be enabled to view this email address), I would change it.
Andrew
09.02.2009Trev, I use Hotmail. So I replace the .(JavaScript must be enabled to view this email address), with my email @hotmail.com.
Is it ok to use hotmail or yahoo?
For the .(JavaScript must be enabled to view this email address), can I use the same email address of mine?
By the way, if sendcopy is checked: if(isset($_POST[‘sendCopy’]), how do you (the code) use the email address supplied into the box for sending email.
Thanks so much for your quick response. Only, if possible, be more detail. Thanks again.
Good luck Trev!
Trevor
09.02.2009@Andrew-
You can use whatever email provider you want; it is using the server to send the mail.
The code is already in place to send a copy to the person if they check the box.
ahmed hamouda
09.08.2009It is fantastic but It doesnt deliver mails from domains
only from hotmail etc but no mains from .(JavaScript must be enabled to view this email address)
I wonder how to fix it.
Trevor
09.08.2009@ahmed hamouda-
What do you mean it doesn’t deliver mail from domains? It works perfectly fine when I test it. Are you testing it locally?
Ahmed Hamouda
09.08.2009I meant that when the sender’s email aint from an official web mail server it doesnt arrive
f.e when I sent an email and the sender email was .(JavaScript must be enabled to view this email address) it didnt arrive
when I used sth like my domain email
.(JavaScript must be enabled to view this email address) it didnt arrive.
Even with the Bug you made a wonderful Job ..
Ahmed Hamouda
09.08.2009My bad
I receive my messages in a gmail account
and I use thunderbird and it considered all the emails like spam so it didnt appear in the thunderbird inbox
Agian dude you are awesome xD
May be I will write about it in my arabic blog after translating your post ofcourse
Thanks alot for this awesome trick
Best Regards ..
David
09.09.2009I think this is great. Just having an issue.
For some reason when I try to test this, the email does not come to my inbox. I checked my spam folder also, just in case. Nothing there either.
I did verify my email was working by installing a contact form plug-in. It worked, I just cannot get this to send the email to myself.
Am I doing something wrong possibly?
Thanks,
David
Trevor
09.09.2009@David-
Not sure what to say, there must be something going on with your setup. Can you get regular PHP mail to work on your server? That’s basically all this is doing.
David
09.09.2009Yes it works fine.
I even had a different script that worked but not within the wordpress environment.
So I found this and it seems to be a step closer, I even get the confirmation message. Just no email received…
Wierd.
- David
Trevor
09.09.2009@David-
Do you have Firebug? What do you see in the POST request?
David
09.09.2009comments Hola Senior
contactName David
email *my correct email address*
submitted true
Trevor
09.09.2009@David-
And you have updated the $emailTo variable in the script to send to your email address?
David
09.09.2009@Trevor
Yes, I have.
$emailTo = ‘MYEMAIL@MYDOMAIN.COM’;
$subject = ‘Contact Form Submission from ‘.$name;
$sendCopy = trim($_POST[‘sendCopy’]);
$body = “Name: $name nnEmail: $email nnComments: $comments”;
$headers = ‘From: My Site ’ . “rn” . ‘Reply-To: ’ . $email;
Kinda hard to show it without giving the world my email address…
-D
Ozh
09.22.2009This is highly dumb. Instead of coding a one-piece HTML / PHP tag soup, use a plugin. It’s more flexible, more easy to share.
Duh.
Trevor
09.22.2009@Ozh-
Wow, thanks for contributing to the discussion.
I am not happy with the code that the contact form plugins create, and I prefer to have 100% control over the code being output on my site. This is why I would rather write the code myself.
Menza
09.25.2009Good work Trevor, great post.
RE: Ozh’s comment:
Mate it’s your choice if you do a plugin or you post on how to do a contact form template. The good thing is that you have published it for anyone to use.
If people cant use your code, they have a choice to use one of the other form plugins.
phil
09.29.2009Hi, thanx for the great tut. I am just working on an implimentation, and thing arose. Since 2005 umlauts and a lot other utf entities can be a part of domains as well as e-mail addresses. now, i want to use you’re form on a german site, ergo umlauts are possible to occur.
I was trying to find a reg-exp. to validate e-mails with umlauts, etc. but could not find anything useful yet.
Do you have any idea where to look for such?
Thanx in advance.
Trevor
09.29.2009@phil-
Not sure I know the answer to that question. I would try Googling around and seeing what you can find; I’m sure someone else has run into a similar problem.
Jodie
10.06.2009Fabulous solution! Thank you!
David
10.20.2009Just wanted to say thanks for this Trevor, it’s helped me a lot today.
And well done for being so patient with your commenters :-)
Maybe some of the issues people are having with receiving mails could be resolved by adding a more fulsome set of mail headers?
return-path, x-mailer, x-sender-ip etc and I’ve seen issues with mail needing to specify ini-set.
Hope that’s useful to someone. Thanks again.
Trevor
10.20.2009@David-
Awesome, thanks for the tips. Hopefully that will help some people out.
don luttrull
10.28.2009thank you for the code and tips, will test this out.
Kevin
11.05.2009Trevor! thank you for this, I was able to hard code it to a page. however my form doesnt seem to be sending out emails. I added my email address to the code but it doesnt seem to work.
if(isset($_POST['submitted'])) {
//Check to see if the honeypot captcha field was filled in
if(trim($_POST['checking']) !== '') {
$captchaError = true;
} else {
//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']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'queesy@gmail.com';
$subject = 'Contact Form Submission from '.$name;
$sendCopy = trim($_POST['sendCopy']);
$body = "Name: $name nnEmail: $email nnComments: $comments";
$headers = 'From: My Site ' . "rn" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
if($sendCopy == true) {
$subject = 'You emailed Your Name';
$headers = 'From: Your Name ';
mail($email, $subject, $body, $headers);
}
$emailSent = true;
}
}
} ?>
Thanks,
Your email was successfully sent. I will be in touch soon.
There was an error submitting the form.
<form action="" id="contactForm" method="post">
Name
<input type="text" name="contactName" id="contactName" value="" class="requiredField" style="margin-left:10px;"/>
Email
<input type="text" name="email" id="email" value="" class="requiredField email" />
Comments
<input type="checkbox" name="sendCopy" id="sendCopy" value="true" />Send a copy of this email to yourself
Submit »
it submits just fine says it sent, but i dont see it in my inbox =(
Kevin
11.05.2009i can get it to work HERE: http://ampersandbox.net/?page_id=130
but not HERE: http://ampersandbox.net/?pg=about
was hoping i could do it outside a page template…. didnt think there would be much difference…. =(
Trevor
11.05.2009@Kevin-
I can’t really debug why emails aren’t sending. You may have to check your email settings on your server.
kevin
11.05.2009@Trevor-
nevermind , basically it did not work because i tried to hard code it into my indexphp. showed up fine but would not send emails so i just made a page template liek you suggested
skot
11.12.2009Hello Trevor,
I love your contact form but can’t for the life of me get it to call your .Js file. Can you take a look at scottbarrettdesign.com and let me know of any problems you can find? It submits the form via email just fine but without the bells and whistles of the js. Thanks in advance for your assistance.
Skot
Trevor
11.12.2009@skot-
I don’t see where in your page you are including the jQuery to validate the form.
skot
11.12.2009@Trevor-
Thanks for the quick response. I’ve been swapping js files and my header.php so much, I had the wrong one in at the time I asked you to check. Its in there now but still no results. Please let me know if you can find the problem. Thanks for the help, Trevor.
Skot
Trevor
11.12.2009@skot-
Looks like you are missing a single quote:
Error: unterminated string literalSource File: http://www.scottbarrettdesign.com/wp-content/themes/sbdNash/js/contact-form.js
Line: 21, Column: 159
$(this).parent().append(<img src="http://www.scottbarrettdesign.com/images/content/2009/11/loading.gif" alt="Loading…" height="31" width="31" />);
skot
11.13.2009@Trevor-
Thanks for the efforts, Trevor. Still can’t get it to display correctly though. If you get a chance, please try taking one more look and I’ll leave you alone o/
Trevor
11.13.2009@skot-
It looks like you are using jQuery with noConflict. If you look at the way that you are loading the cycle plugin:
jQuery(document).ready(function($) {$("#rotator").cycle({
fx: 'fade',
timeout: 3000,
speed: 1000,
pause: 1,
fit: 1
});
});
You will need to do the same for the contact form.
skot
11.13.2009Thanks a million, buddy. Look forward to more tuts from you. Consider you bookmarked ;)
peter
11.24.2009how about adding checkboxes,
and none required fields?
everything else works, but i cant get it working…
<b>Zumba toning WORKSHOP</b>
<input type="checkbox" name="earlybird" value="147.50 " onclick="this.form.total.value=calculateTotal(this);" />
"Early bird" tarief a 147.50 Euro
VES ZIN Member a 147.50 Euro
Normaal tarief a 180 Euro
<b>Extra </b>
geen gebruikmaken van lunch buffet
wel gebruikmaken van lunch buffet incl. koffie/thee en melk a 11.- Euro
<strong>Totaal:</strong>
peter
11.24.2009cant get the checkboxes to show either…
http://www.pasteall.org/9390
Trevor
11.24.2009@peter-
I’m not sure what you are asking.
peter
11.24.2009how do i get to see if someone hits a checkbox, and especially what checkbox
and the content of a autogenerated textfield
i need to get those values into the email
thanks in advance!
Trevor
11.24.2009@peter-
You just need to use the name attribute of the form fields to access the data. Then, you can access them in the $_POST array.
peter
11.25.2009http://www.pasteall.org/9411
nothing happens…
Trevor
11.25.2009@peter-
I’m sorry, I can’t walk every person through their specific issues in their forms. If you are interested in more in depth help, you can hire me by contacting me directly.
Ana
11.26.2009Hi Trevor,
I just implemented your template and it works great.
I have just one question: I’m using it in a Portuguese website and I’m getting problems with the text encode when I receive the emails submitted.
Special characters - accents, cedilla, etc - aren’t displayed correctly. And line breaks appear with symbols (they are displayed by the entity name).
Do you know how can I add character encoding to the sent emails?
Thanks!
Gian
11.27.2009Hi Trevor,
I’ve been looking so much for a way to manage forms WITHOUT having to use a plugin and have total control of the code. So, first of all, thanks for putting up the only tutorial on the whole web about such a thing.
Sadly, I too can seem to be able to send emails from WP. I am at MediaTemple and the server send it fine when outsdode of WP. I just copied your template file, changed the email address, linked the JS, but don’t get emails.
I need this so much to work, as it’s the laste step vefore I publish my site, and if I can’t get a simple form to send an email, I cannot publish the site.
Strangly enough, at some point I recopied all the code from the tutorial, and at some poitn it did manage to send teh email. So that mean that something made it work, but now, again, without any change, it just doesn’t send anything anymore.
If you want I can provide a link to the development site, but I prefer to send it to your mail (don’t want to make it public ‘til the site is in dev phase).
Thanks for the help.
Gian.
Trevor
11.28.2009@Ana-
You can pass in additional headers in the mail function to specify the charset.
@Gian-
Does the email send when you are not using JavaScript? Is it getting caught in your spam folder?
Joe
12.03.2009Great sample code. Thank you.
Do you have any guidelines for adding a type=FILE field to this form? I tried to do so and have run into some issues:
1) The incoming type=FILE field on my contact form is optional, but if I do generate errors on other required fields on the same form then I am unable to refill the contents of the type=FILE field - as your code does for the other fields in your example.
I believe this is due to an HTML security feature to prevent websites from pre-filling FILE fields - but in my case if a user fills out a form - including selection of a local file to upload in a type=FILE field - and then clicks SUBMIT, and then subsequently gets an error on some field other than the FILE field, then I am unable to refresh the type=FILE field and they will need to be reminded that they need to re-select their optional FILE field that they had filled in the first time around.
In other words, upon detecting errors in your current contact form you currently always refresh all incoming fields so that the user does not need to re-enter them when one or more edit/missing errors are detected. But type=FILE fields cannot be refreshed in this manner. And since my type=FILE field is optional then I cannot always simply check that it was filled in.
How would you handle that issue?
2.) As I am just creating this new contact form with a type=FILE field I am noticing that when processing the incoming form data that I am unable to access the path or file contents in either
$_FILES[‘fieldname’] [‘name’]or$_FILES[‘fieldname’] [‘tmp_name’].I can, however, access the uploaded file’s name in
$_POST[‘fieldname’]Do you know of any reason why these values are not accessible when I am processing the incoming form? I successfully can access all the other incoming form fields, as well as the actual file name of the type=FILE field, just not the full pathname nor the file contents itself.
Joe
12.03.2009@Joe-
I just figured out Part 2 of my issues: I couldn’t access the file data because I had not included the pesky “enctype=multipart/form-data” on my FORM statement.
I still could use advice on my issue #1 - how to handle an optional type=FILE field if errors occur on other fields
Trevor
12.04.2009@Joe-
I guess you could upload the file to the server regardless if there are errors in the form or not.
abdul chalik
12.07.2009nice, thanks man
Alex
12.15.2009Hey, nice tutorial, I managed to make the form work but i have a slight problem. When I send out a email, I receive 2 identical emails inside my inbox. Do you know what is causing this?
Thnx
Trevor
12.15.2009@Alex-
Are you checking the box to send an email to yourself?
Alex
12.16.2009No, I am not. Simply, when I press the send button in the recipient`s inbox i receive 2 identical emails. I checked the code but it`s nothing wrong.
Trevor
12.16.2009@Alex-
Do you see 2 requests in the Firebug console? Is it submitting the AJAX request and then the regular request?
If not, you may want to talk to your host about it.
Torsten
12.22.2009Hello Trevor,
I really like this code. But there is a little problem if I try to expand the abillity to send emails to different recipients.
In WordPress I use the Custom Fields to set an email adress. I call the page using your template as url with parm:
.../?mailempfaenger=” target=“_blank”>Mail an den Inserenten</a>In your template I can read this by using the following code:
$empfaenger = htmlspecialchars($_GET[“mailempfaenger”]) . ‘’;If I echo it in your code before displaying the form, the email-adress is shown correctly.
I ‘ve set the variable $emailTo to $empfaenger
As if the mail was not sent, I tried to echo the variable $emailTo. It seemd to be empty. Also I tried to set it’s value by using:
$emailTo = trim($_GET[‘empfaenger’]); and
$emailTo = trim($_POST[‘empfaenger’]);
Both did not work.
Do you know, how I can retrieve the value from inside your script, so I can use it as email adress where the form should be sent?
Thanks a lot.
Torsten
Trevor
12.22.2009@Torsten-
I am not sure what you are trying to do here. This is just regular PHP here, nothing fancy, so I’m not sure why your code isn’t working.
Denys
12.24.2009Hi, Trevor.
Thanks for great tutorial,very helpful.
Please explain me how to change the style of submit button. I want to use only “” without “” and I don’t wanna use the tag “” . When I delete all unnecessary tag mail stop delivering. I think there need to change contact-form.js file but I don’t know HOW.
Please help me!
Sorry for my english.
Denys
12.24.2009Oops!
I want to use only “input” without “button” and I don’t wanna use the tag “li” .
Trevor
12.24.2009@Denys-
Not sure what you mean that you don’t want to use an li tag, but here is the code you would need to modify to use an input instead of a button:
$('form#contactForm li.buttons button').fadeOut('normal', function() {$(this).parent().append('<img src="/wp-content/themes/td-v3/images/template/loading.gif" alt="Loading…" height="31" width="31" />');
});
Denys
12.24.2009@Trevor-
Thank you! I know that but dont know how to modify.
If I delete li tag in html i must modify this line in js file
$(’#contactForm li.buttons button’).My html for submit button looks like
<code></code>
How I should modify my js code for this html?
Denys
12.24.2009oh mine God!!!Sorry.
My html for submit button looks like
‘input type=“submit” name=“button” id=“button” value=“Submit” />’
Trevor
12.24.2009@Denys-
Just use the id of your submit button.
Denys
12.24.2009Trevor delivery isn’t working.
I’m trying to use “form#contactForm #button”, “#button”, “button”.
Trevor
12.24.2009@Denys-
I don’t know what you mean. Where are you trying to use this? What’s not working? Does the form submit? If you want help, you need to be more descriptive and clear about what is not working or what you are trying to accomplish.
Denys
12.24.2009I had a ready html form, I decided to add ajax in accordance with your tutorial. Everything has changed, except the button submit. Letters come on a box only when the button html-code is not changed. If I try anything to change letters stopped coming to the box, the form sends but I do not receive letters. How it is interconnected I do not understand.
Torsten
12.24.2009Hello Trevor,
well, of course, it’s regular PHP. But the Problem is, I don’t know, why the code
$empfaenger = htmlspecialchars($_GET[‘mailempfaenger’]) . ‘’;works if I place it in the beginning of your script (line 6) but don’t if it’s placed later (after the line 50). Do you know which mistake I’ve made?echo $empfaenger;
I thought “$_GET” is superglobal, so it should work everywhere?
Thanks for your help.
Trevor
12.26.2009@Torsten-
I don’t see why it wouldn’t work.
@Denys-
Can you provide a link?
Denys
12.29.2009@Trevor-
Thank you! I think this help
Trevor
12.29.2009@Denys-
The form submitted fine for me.
Denys
12.29.2009For me too, but mail doesnt sending. With your design all fine but with some trouble. I dont know why.
Trevor
12.29.2009@Denys-
You should try contacting your host then or double check the PHP code to make sure you are sending to the right address.
Denys
12.29.2009Maybe you dont understand me. The form stop sending only after two changes. 1) Styling the SUBMIT button and 2) changes in js file in this lines :
$('form#contactForm li.buttons button').fadeOut('normal', function() {$(this).parent().append('');
});
Before this mail is coming. In both methods form the form is submitted. I think host and PHP isnt guilty.
Trevor
12.29.2009@Denys-
Sorry, I can’t debug every individual problem. If you would like me to, then you can hire me.
CosyDale.com: WordPress MU ? BuddyPress
01.05.2010?????????? CD.com ?? WP 2.9…
????????? ?? ?????? WordPress 2.9. ???? ????????? ??????????? ?????? Simple Tags, ?? ? ??? ???????? ?????? ? ?????? ?????????. ??? ???? ? ????? simple-tag?.php (? ????? ???????) ????? 2.7 ???????? ?? 2.9 ?? ?????? 35. ? ???… ??? ??? ???? ???? ?? ...
Denys
01.07.2010Hi Trevor!
I have the problem with error messages. Message show text but dont show label name at the end of message.
Looks:
You forgot to enter your .
I dont touch js file. How fix it?
Thanks.
Trevor
01.08.2010@Denys-
It depends on your markup. It is grabbing the value from the text in the label.
Denys
01.08.2010@Trevor-
All your labels is saved. I dont change label name.
Trevor
01.08.2010@Denys-
I can’t help you if you don’t provide more details or a link.
Denys
01.12.2010@Trevor-
See this link
Tell me can I delete your js validation and use some plugin for that.What and how I need to change in contact-form.js ? Thank you!
Trevor
01.13.2010@Denys-
You completely changed the markup of your form, which the JavaScript validation depends on.
Julie
01.14.2010Trevor, I’ve been digging around in the css for a while and for the life of me I can’t figure out how to get rid of the border around the checkbox.
It shouldn’t be there since the border style only applies to ol.forms input, ol.forms textarea.
Also, I’m having trouble getting the Submit button to align square in the center of the form. I’ve tried text-align: center, tried setting the width to a fixed pixel number and still no luck.
Thanks.
Denys
01.14.2010@Trevor-
I understand. How to delete your javascript validation and keep on javascript submit? Thanks.
Trevor
01.14.2010@Julie-
A checkbox is an input elements, so it will inherit styles being applied to input elements. Try using text-align: center on li.buttons.
@Denys-
Just delete the JavaScript then. There are a million form plugins out there; it seems like mine doesn’t suit your needs.
Denys
01.14.2010I know about all plugin out there,but at this time sending email normally only your form. At this time I need some changes with submission and validation. For validation I want to use some plugin like “jquery validation”. I cant delete your javascript because that delete a function “submit without refreshing page”. I’m truying delete this lines:
var hasError = false;$('.requiredField').each(function() {
if(jQuery.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('You forgot to enter your '+labelText+'.');
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('You entered an invalid '+labelText+'.');
hasError = true;
}
}
});
if(!hasError) {
After this form submiting always when push on submit button even when form is cleared. Im just want to use your form with javascript submition but with my plugin validation. How to do this? What lines I must delete,change? Thank you!
Trevor
01.14.2010@Denys-
There is a limit to how much support I can provide to every person; you are basically asking me to do your work for you. If you are interested in that, you can hire me.
Denys
01.14.2010I’m asking because dont understand javascript. Thanks for form.
Keith
01.15.2010Hi,
I’ve been looking for a form with a send to yourself feature for ages, so excellent to find this site. Just wanted to check to see if I can use this form for a non wordpress website? Guessing as it is not a plug in then it should be ok.
Trevor
01.16.2010@Keith-
Yeah, you should be able to use it on just a regular PHP site too.
Paul Versteeg
01.16.2010Very nice! Thank you
Julie
01.17.2010Trevor, I appreciate your input. I had some things that apparently override the “text-align: center” for the buttons. Got rid of that - now it works.
Another question - I’m now trying to implement a jQuery hide/show function where the “billing address” section is hidden unless the user checks a checkbox that says “my billing address is different than my mailing address”. I’m so new to php and jQuery that I’m really stuck in the basic syntax.
This is what I have written in the .js file:
jQuery(document).ready(function () {jQuery('$billAddress').hide();
jQuery('$billShow').click(function() {
jQuery('$billAddress').hide();
if(jQuery('$billAddress').css('display')=='none') {
jQuery('$billAddress').show(); } else {
jQuery('$billAddress').hide(); }
});
Now, I have no idea how to tie this to the checkbox in the .php file.. I’ve started with your basic checkbox from the contact form but I don’t know where to go from there..
<input type="checkbox" name="billShow" id="billShow" value="true" />My billing address is different from my mailing addressThanks so much for all your help!
Julie
Julie
01.17.2010Sorry.. it seems part of my code was cut off.. it’s the same as your contact form checkbox code, only the id is changed to “billShow”.
Paul Versteeg
01.17.2010hi,
When submitting your great form, i get two “thanks” messages displayed and the email is also sent twice.
I’ve checked for any duplicate code, but I can’t seem to fix it; any idea what i’m doing wrong??
thanks,
Paul
Trevor
01.17.2010@Julie-
Your syntax is not correct.
jQuery('$billAddress')Is not going to select anything. You should review the available selectors.
@Paul Versteeg-
Maybe you are getting a JavaScript error somewhere after you submit the form. So it sends the email via AJAX and then without AJAX. Not really sure what else it could be.
Julie
01.17.2010Trevor, thanks for pointing me in the right direction. After some more studying and Googling I found this to have worked for me:
jQuery(document).ready(function() {
$('form#ftpForm .billDiff').click(function() {
$('form#ftpForm .hideThis').toggle("slow");
});
});
Thanks again!
Marko
01.17.2010I want to thank you too, your method is really great, already use it on my blog. Great post, great contact form.
Julie
01.18.2010Trevor, I hate to keep bugging you but I’ve Googled and read the web all day and I’m no closer to a solution.
My problem is now that the “Billing Address” fields are hidden on page load by the .js, if there is an empty field and the user submits the form, the page reloads with the error messages appropriately, but the “Billing Address” fields stay hidden. When I click the checkbox to show these fields, the errors are there.
Do you have any idea, how to save the “checked” state of the checkbox on browser reload (thus keeping the hidden fields visible with errors), if the form doesn’t submit due to missing fields?
Thanks so much for your help!
Trevor
01.18.2010@Julie-
There are various methods to accomplish what you want to do. I would probably check to see if the checkbox is checked before hiding the fields with JS.
Julie
01.19.2010I’m still a bit confused, though.. I thought this bit of code:
<code></code>
would retain the checkbox’s checked state when the form was attempted to Submit (as it also kept the values inside the text fields)..
if that’s true, then it must be something in my JS file that overrides that?
Julie
01.19.2010sorry.. :)
Trevor
01.19.2010@Julie-
I can’t really comment on what your form should do without seeing it. I have no idea how you have coded your form.
Tolga
01.27.2010thank you very much, it’s awesome tutorial
ven
02.01.2010i like this article followed all the steps , skipped jquery part.
basic question , when i click on submit button .
i get 405 error resource not found .
action=”” still does not work.
if i remove
if(isset($_POST[‘submitted’])) {
works fine .
thanks
Trevor
02.01.2010@ven-
Sounds like you may need to contact your host about that error. Without seeing the link to your page, I can’t help at all.
ven
02.01.2010ok . now all my pages are redirecting to static home page. i think this is related with wordpress settings.
ciprian
02.03.2010Wow that’s a great tutorial! Thanks for sharing!
I have a question: is it possible to send the message to multiple e-mail addresses?
Do you have to separate the addresses with a comma or something?
I am asking this because I implemented the form into a wordpress theme and I am grabing the email address from the wordpress admin area: I created a custom function that adds me a field in the admin area where I can add the email address, and isted of calling $emailTo, I call for my custom function:
$headers = ‘From: My Site ’ . “rn” . ‘Reply-To: ’ . $email;
mail($custom_function, $subject, $body, $headers);
Everything works just perfect if I only add one email address. But if I add more than one address, I won’t recive any emails… I separated the email with a comma.
Any ideeas how this might be worked out?
Thanks in advance!
ciprian
02.03.2010No worries! I solved the pb: there has to be a space in front of the comma:
.(JavaScript must be enabled to view this email address) , .(JavaScript must be enabled to view this email address)
Thanks again!
Steven Gun
02.12.2010Great tutorial! Everything works like a charm with one little but bothering exception: the mail is sent twice.
The funny thing is that i get 2 different emails: one containing only the standard fields (name, email, comments) and another one containing the standard fields and all my custom added fields.
Please help me out cause I am so lost in here…
No jquery, it is only php (or at least that was my intention)
Steven Gun
02.12.2010here is a link to the contact form:
http://webdesignpro.ro/?page_id=294
Trevor
02.12.2010@Steven Gun-
Maybe you call the mail function twice? I have no idea I can’t see your PHP.
De
02.16.2010Awesome Tutorial
Jared
02.22.2010@Trevor
Why are there two forms of validation, jQuery and PHP? If jQuery validates the fields, then why do you need to have all that extra code on the back end?
ciprian
02.22.2010@Jared
What if javascript is disabled? :)
Trevor
02.22.2010@Jared-
Because if a user turns off JavaScript, you should still validate the form.
Jared
02.22.2010Yeah, I guess that was a stupid question.
I never considered a user turning off javascript. (Newer browsers, like Chrome for Mac don’t even have that option available. Not that this is a reason for not having a backup validation, just an observation. )
Andrew
02.28.2010Trevor,
I copied all your codes above, modified the email addres. Everything seems correct, including the <script type="text/javascript" src="<?php bloginfo('template_directory in the header.php
BUT, unfortunately, I NEVER RECEIVE the email
Can you please solve the problem, Trevor?
Thanks
Andrew
02.28.2010Have you updated or MAKE SURE the JS code works?
Trevor
02.28.2010@Andrew-
Do you have a link to the page? Is it working without JavaScript enabled? Is it getting caught in your spam folder?
Andrew
03.01.2010Firstly, thanks so much for your reply. Thank you
I used Windows Live Mail. And the email address I use to replace the .(JavaScript must be enabled to view this email address) is Hotmail account.
In this experiment, both the email adress that replace .(JavaScript must be enabled to view this email address) and the email address that I inputed in the input box, are listed on the Windows Live Mail. So I believe, these 2 emails have been recognized by the Windows Live Mail
And as you know, the Windos Live Mail has Junk Email Folder. So I think even if the 2 emails are not recognized, they will still arrive as junk emails
BUT, they are not, Never arrive
Perhaps there is a solution for this problem
Thank you Trev
Trevor
03.01.2010@Trevor-
What is the link to the page? Is it working without JavaScript enabled?
Andrew
03.01.2010I do locally with Wamp. I’m sorry there is no link, other than http:/localhost
When I experimented by removing (deleting) these 2 lines from header.php”
<script type="text/javascript" src="/scripts/jquery.js"><script type="text/javascript" src="/scripts/contact-form.js">
Followed by refresh, input my nama again in the input box, click send, then there is ERROR message:
Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost, an so on, on line 56
FYI, line 56 on my Contact-Form.Php file, has the following:
mail($emailTo, $subject, $body, $headers);Is this the one that you try to diagnose? (you asked: Is it working without JavaScript enabled?) Then seemingly the answer is NO.
Kindly please suggest, concrete steps that could solidly solve the problem.
Thank you Trev
Trevor
03.01.2010@Andrew-
Sounds like you don’t have a mail server setup locally.
Andrew
03.01.2010Trev,
What do you mean with Local Mail Server? You mean something in PhpMyAdmin? or the SETTING at Windows Live Mail 2009
Thanks once again for your reply
Trevor
03.01.2010@Andrew-
You are using Wamp to run Apache/PHP/MySQL correct? You need to have a mail server, hence this error:
Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost, an so on, on line 56
Andrew
03.01.2010Remember that error message appears when I remove the JavaScript link at Header.Php.
When the link to JavaScript at Header.Php is not removed, the process runs smoothly, Thank You message appears as usual:
Thanks! Your email was successfully sent. I check my email all the time, so I should be in touch soon.
BUT THE ONLY PROBLEM, the email never received, or perhaps never sent.
Any brainstorm?
Trevor
03.01.2010@Andrew-
The error does exist when you have JavaScript enabled, just look at the Firebug console and see the request. The problem is that you don’t have a local mail server configured.
Andrew
03.01.2010Thanks Trevor,
Im sorry, im a newbie, what do you mean about Firebug console? where it is located?
BTW, Trev, this is to clarify about the error message: Warning: mail() [function.mail]: Failed to connect to mailserver at “localhost, an so on, on line 56
That error message appear WHEN the JavaScript is NOT exist.
When your JavaScript is exist, the error message is not appear. When the link to your JS is exist, the Thank You message will appear smoothly (Only after that, no emails received)
Trevor
03.01.2010@Andrew-
This is Firebug. If you actually read the JavaScript, you can see that the thank you message appears no matter what. It does not checked to see if the request is successfully completed before displaying it.
I don’t know how else to say it: the problem is that you do not have a local mail server configured.
Andrew
03.01.2010Thanks Trev,
At least there is guidance,despite still blur, no idea, about firebug. I recognize the word Firefox (browser) but not firebug
I will come back again tomorrow
Thank you so much
Phil
03.03.2010Hello Trevor,
Thank you very much for taking the time to contribute to the community.
My question is: Is it possible to create validation for drop-down menus? I tried leaving the first option blank to play off of if(subjectVal == ‘’) and tried using the id selector in the and tags for the menu. I got nothing. I’m new to this so that’s as far as I can go.
Phil
03.03.2010Okaay, I feel silly. I over-thought this and overlooked that I had value=“text” in the option tag when it should have been value=”“. Can’t believe I didn’t see that. Anyway, the answer to the question is yes it is possible.
Andy H
03.03.2010Thanks for excellent article!
The form validation does not work when using AutoFill http://github.com/joemsak/jQuery-AutoFill It thinks that there’s text already in the field (expect for textareas). Any idea how to get it to play along?
Nice to see so well written articles and friendly comments :)
Trevor
03.03.2010@Andy H-
I would probably consider using a different in field label plugin that does not add values to form fields.
Andy H
03.03.2010By the way, my form nor your demo are not sliding up after submission. I tested it with FF 3.6 and Safari 4. Any ideas. Thanks again!
Trevor
03.03.2010@Andy H-
Not sure, maybe something has changed in the new version of jQuery.
alexut
03.04.2010Hey Trevor, i wonder if i could add a default value, like “Type your email here” in the input without messing to much with the code?
Thanks
Trevor
03.04.2010@alexut-
I just wrote an article about that.
alexut
03.04.2010heh you just gave me another reason to hate internet explorer 6,7 and 8, the font is stripped of the rendering in ie when applied the opacity, i was using a big font and it’s looking hideous.
Huroman
03.05.2010Hi, there. You’re script works excellent, but i want a special option, i’ve been trying around hours but with no success.
I need a drop menu for multiple recipients (emails), similar to your but without lucky.
The example:
Contactar a
Ventas
Comentarios
Dudas sobre el negocio
Soporte de Producto
Conocer el negocio
Iridología
Biomagnetismo
Abrir un Centro de Distribución
Do I need to add a couple line code like this?
if($sendCopy == true) {$subject = 'You emailed Your Name';
$headers = 'From: Your Name ';
mail($email, $subject, $body, $headers);
}
Huroman
03.05.2010I miss the code to insert it in this post, sorry =o
The example:
Contactar a
Ventas
Comentarios
Dudas sobre el negocio
Soporte de Producto
Conocer el negocio
Iridología
Biomagnetismo
Abrir un Centro de Distribución
Do I need to add a couple line code like this?
if($sendCopy == true) {$subject = 'You emailed Your Name';
$headers = 'From: Your Name ';
mail($email, $subject, $body, $headers);
}
Trevor
03.05.2010@Huroman-
I don’t understand what you mean. But yes, if you want to send multiple emails, that is the section you will want to edit.
Huroman
03.05.2010Thank you for your reply and sorry for the bad tags.
Well, your scripts runs perfect but i want to send the email/comment to different email’s departments (Support, Sales, Business, Reports, etc). I’ve been reading and trying but nothing.
I need an option to select recipients by drop box menu or radio option, doesn’t matter. This is the idea:
- Select one Department:
Option 1: .(JavaScript must be enabled to view this email address)
Option 2: .(JavaScript must be enabled to view this email address)
Option 3: .(JavaScript must be enabled to view this email address)
and so…
The idea (it doesn’t work, of course):
http://huriata.com/cuentas/be/contacto/formulario
Thank you in advance. If it works, i could post all the code to share it and help others.
Trevor
03.05.2010@Huroman-
So just check the values of that form field and send to whomever you want depending upon which option was selected.
I’m sorry I’m not going to write the code for you unless you would like to hire me.
Donald Jenkins
03.06.2010Looks like the new version of jQuery prevents the form from sliding up any more.
Pity really. If anyone has fix, I’d be interested.
Andrew
03.07.2010Hi Trev,
How to configure a Local Email Server?
Thank you
Donald Jenkins
03.07.2010I like this form quite a bit, but the javascrpt not working made it pretty dysfunctional: so I removed the call to the javascript and let the template’s conditional structure to display the appropriate page. Simpler and even less bloat, which is what I was looking for in the first place when I ditched my contact form plugin in favor of this solution.
Andrew
03.08.2010Hi Trevor,
In my previous posts, I mentioned that I have put my hotmail email account to replace the “me@somedomain.com” correctly, but the problem is I never receive the email (or probably) never send the email.
You said thats because I have not configured LOCAL MAIL SERVER. Can you please explain how? or at least shed some lights about directions to the solution of the problem using your codes that in fact never receive the email?
Thanks Trevor,
Andrew
Trevor
03.08.2010@Andrew-
This really is not the appropriate place to ask about how to set up a local mail server. Try Googling it.
Mike
03.08.2010Hell yea, this is what I need. I hate that cforms crap and all those garbage plugins. Makes it so hard to control the markup and figure out where the CSS is coming from. This is great, with the honeypot, jquery, and all the fixings…but simple too.
Michael
03.10.2010Hi, Great code.
I am having a little problem and dont know why. I have put all the code together but when i click submit on the site i am currently working on i get this come up on a new page;
Parse error: syntax error, unexpected $end in /homepages/44/d242893647/htdocstests/test1/Contact/contact-form.php on line 170
Any advice would be much appreciated!
Trevor
03.10.2010@Michael-
You’ve got a syntax error in your PHP. So go to that line in the file and fix the error.
Roger Stanton
03.15.2010@Trevor-
Have I mentioned once or twice before how much I love your direct approach with advice giving? lol
Kurt
04.08.2010Trevor:
Great tutorial! I’m wondering how you set it up to use the default/admin email?
Thanks!
Kurt
04.08.2010@Kurt-
I should clarify: I want to use a function so I don’t have to change the template if the admin email changes.
Trevor
04.09.2010@Kurt-
Use get_option().
Kurt
04.09.2010@Trevor-
Thanks. I should have been able to figure that out.
Ludz
04.14.2010This seems like a great script but i cant get it to work. The form seems to submit without errors and all the mail settings seem to be correct in PHP. One thing i did notice is that we are running a 64bit version of windows. After doing a bit of reading i have found other people having problems with mail sending on 64bit windows.
My simple question is, is this something that should work on 64bit windows? If not, does anyone have any ideas on what i can try to get this working?
Nick
04.28.2010Hi Trevor,
I am trying to implement this in my wordpress theme. I tried first on my local server and I could see the values in the $_POST after calling $.post
But same thing, I cannot see in my actual web server when i uploaded my theme. $_POST variables are empty. Do you know what could be the reason for this ?
Trevor
04.29.2010@Nick-
Not sure, sounds like a configuration issue on your server.
Andreas Lindberg
05.10.2010Hi
I have implenent the contact form in the website.
I have bulit a long form, I want it to jump up to the field that are not feld. When the user has don something wrong. How do i do that.
sorry for bad language
John MacMenamin
05.18.2010I would love you work on some nice vanilla css to add to an 2.0 update for WP 3.0.
You could sell this on Code Cannon too if you want.
I got this wonderful script working on WP 2.9.2 but I’ve tried WP 3.0 with Twentyten and my own custom theme and can’t get it to send.
Anyone have this working on WP 3.0?
John MacMenamin
05.18.2010I got it to send on WP 3.0 once but only when I checked the send me a copy box?
nBall
05.18.2010Trevor, your patience seems to be infinite. Excellent tutorial, I came to the same conclusion as you regarding the multitude of overwrought contact form plugins.
@everyone-asking-for-support: use Google, do it yourself, or hire Trevor. Good grief people.
Trevor, can you explain why my car won’t start?
satishraj
05.27.2010Hi @trevor this is a wonderful blog article which helped me developing my contact us form in the wordpress site and please mail me the links for the other customized topics you are dealing with for wordpress i need them as i am new to this CMS WP this helped me a lot Thanks Thanks alot .
First i got confused by reading this please read it second time with a bit of concentration you will get it and you can implement following the steps.
Thanks post me the new article related to customization of the wordpress CMS
satishraj
05.27.2010Hi trevor i have a problem when i crated a dropdown menu in the menu bar it has 7-8 sub menu items when i am in contact us form,
and then mouse over on menu containing submenu items more that 7-8 they are overlapping with the contact us form fields i am not able to select any submenu item when they are over lapping the text fields of contact us form.
Please answer my question i am waiting for the replay please post it as soon as possible.
Thannks in advance.
raj
06.02.2010Hey trevor ur code is excellent it worked for me if i am not troubling you by asking i have a question how can i store the field values in database instead of sending mail.
I will be very glad if you help me out from this thanks very much .
You have got lot of pateince to answer all the questions they have asked
Thanks Once again for nice tutorial.
Raj:)
Trevor
06.02.2010@raj-
Sure, you would just need to modify the code to insert all of the values into a table instead of sending the email. Just create a new DB table and store the info there.
Raj
06.03.2010Hey thanks for your reply i was able to create database table and not able to insert as i am new to wordpress.
I don’t know much about add_options so if you can help me out by giving a small example to store 2-3 fields into dbtable in coding explanation i will very thankful to you.
Thanks for reply.
Raj:)
Sumit Gupta
06.06.2010Thanks a lot! I was having trouble preparing a decent contact from. This really helped me a lot.
Steve
06.23.2010I love your code, I am having a small problem. The email is not being sent. If I check the send copy, the copy is going to my other email just fine, but not to my main one. Yes I entered the email. Any ideas?
Also, I am not using the js because for some reason it keeps saying valid emails are not valid.
Trevor
06.23.2010@Steve-
Might be a problem with your mail server.
Steve
06.23.2010@Trevor-
Hmm, I am using a hosted exchange service for my email, separate from my webhost. Could that be the issue? Can I even send phpmail in this setup?
Trevor
06.23.2010@Steve-
No clue, there are a lot of variables in mail server setups. Try creating a dummy page that just does a php mail().
David
06.28.2010Great solution to a common problem
Will Dawson
07.01.2010Hey Trevor,
I’ve spent ages searching through all the comments, in hope of an answer, but no luck of a resolution. While I have previously made my own PHP contact form for wordpress, I tried yours as well with no avail.
Unfortunately, I can’t give you a link as I am developing this locally with MAMP. Both mine and your scripts work when used on a page, but not on my index.php page. I troubleshooter for a while and realised it was all in the form action link. If I use the permalink php code, the script works but redirects the page to the first post in the query. If I have the action blank, then the page loads white. If I use ‘index.php’, white. If I use the string, the page will load but no validation will run, and the email won’t send! Haha. I have just tried using the full link to my index.php (theme URL and all), and validation ran along with the email being sent, but that was all that displayed! The rest of my index page dissapeared!
Hope you can help me!! Just need to know what the form action has to be! Or another resolution…
Trevor
07.02.2010@Will Dawson-
I used the permalink in my example. Not sure why your page would redirect to a different page.
Will Dawson
07.02.2010@Trevor-
Well, using it on my index.php page works fine, it will just redirect to the first post (http://localhost:8888/wordpress/projects/example) and send/validate. Just wondering if you could help as you have obviously had more experience with wordpress than I! :) Nevermind if you don’t know, I’ll just have to troubleshoot some more.
——-
Kishore Mylavarapu
07.14.2010Really a great tutorial and a great commenting system implemented on this site..
kilinkis
07.28.2010thx dude, very useful
Jacob
08.09.2010Hey, thanks for the great contact form! I have been working out the kinks in mine as well, but I am a little new to the whole web development process. Am I able to use the functionality of this contact form in themes I would sell? I don’t want to use something without you permission and was just curious. Thanks again, I learned a lot from this!
Trevor
08.09.2010@Jacob-
Sure, you can definitely use this functionality in themes that you sell. If you could just leave an attribution to me and this article, it would be much appreciated.