WordPress & jQuery Contact Form without a Plugin

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 = 'me@somedomain.com';
 $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 Your Name';
  $headers = 'From: Your Name <noreply@somedomain.com>';
  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.

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

CenturyLink Deals: Internet, Phone, & TV Bundles

344 Comments

Buzzlair Voufincci

02.26.2009

mate! 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.2009

I 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.2009

Sure, 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.2009

its awesome!

Olli

03.08.2009

Very 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 {
 
border1px 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.2009

While 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?

Raymond Selda

04.04.2009

Good 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.2009

Wow, that was a great tutorial! Thanks I used it on my blog’s contact page!

jitendra

04.20.2009

After setting up this form i didn’t get any mail in my inbox.

jitendra

04.20.2009

I 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.2009

Great 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.2009

Hi 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.2009

I 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.2009

Great 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.2009

Hi 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.2009

I 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.2009

I meant a tags in the tags and it works great…Go figure :)

stu

05.18.2009

Still 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.2009

It 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.2009

Hi, 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.2009

Trevor,

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.2009

Thank 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.2009

Ok, 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:

General
Booking
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 &lt;

Barton

07.22.2009

Great 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.2009

Thank 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.2009

thank.you!!!

Rhys

08.12.2009

Awesome 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.2009

I 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.2009

sorry code didn’t show :

 

Nort

08.25.2009

thanks 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.2009

yes, 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.2009

Your 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.2009

Hi,

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.2009

Thanx 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.2009

if($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.2009

Trev, 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.2009

It 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.2009

I 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.2009

My 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.2009

I 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.2009

Yes 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.2009


comments 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.2009

This 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.2009

Good 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.2009

Hi, 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.2009

Fabulous solution! Thank you!

David

10.20.2009

Just 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.2009

thank you for the code and tips, will test this out.

Kevin

11.05.2009

Trevor! 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 sentI will be in touch soon.
 



  
  
   
There was an error submitting the form.
  
 
  <
form action=&quot;" id="contactForm" method="post">
 
   
    Name
     <input type=&quot;text&quot; name=&quot;contactName&quot; id=&quot;contactName&quot; value=&quot;" 
class="requiredField" style="margin-left:10px;"/>
     
       
     
    
    
    
Email
     
<input type=&quot;text&quotname=&quot;email&quotid=&quot;email&quotvalue=&quot;" class="requiredField email" />
     
      
     
    
    
    Comments
     
     
       
     
    
    <input type=&quot;checkbox&quot; name=&quot;sendCopy&quot; id=&quot;sendCopy&quot; value=&quot;true&quot; />Send a copy of this email to yourself
    
    Submit &raquo; 

it submits just fine says it sent, but i dont see it in my inbox =(

Kevin

11.05.2009

i 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.2009

Hello 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:

Errorunterminated string literal
Source File
http://www.scottbarrettdesign.com/wp-content/themes/sbdNash/js/contact-form.js
Line21Column159
$(this).parent().append(<img src="http://www.scottbarrettdesign.com/images/content/2009/11/loading.gif" alt="Loading&hellip;" 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',
     
timeout3000,
     
speed1000,
     
pause1,
     
fit1
 }
);
}); 

You will need to do the same for the contact form.

skot

11.13.2009

Thanks a million, buddy. Look forward to more tuts from you. Consider you bookmarked ;)

peter

11.24.2009

how about adding checkboxes,
and none required fields?

everything else works, but i cant get it working…

<b>Zumba toning WORKSHOP</b>
        <
input type=&quot;checkbox&quotname=&quot;earlybird&quot;   value=&quot;147.50 "  onclick="this.form.total.value=calculateTotal(this);" />
      &quot;Early bird&quot;  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.2009

cant 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.2009

how 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.2009

http://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.2009

Hi 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.2009

Hi 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.2009

Great 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.2009

nice, thanks man

Alex

12.15.2009

Hey, 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.2009

No, 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.2009

Hello 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.2009

Hi, 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.2009

Oops!
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.2009

oh 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.2009

Trevor 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.2009

I 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.2009

Hello Trevor,

well, of course, it’s regular PHP. But the Problem is, I don’t know, why the code $empfaenger = htmlspecialchars($_GET[‘mailempfaenger’]) . ‘’;
echo $empfaenger;
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?
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.2009

For 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.2009

Maybe 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.

Denys

01.07.2010

Hi 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.2010

Trevor, 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.2010

I 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.2010

I’m asking because dont understand javascript. Thanks for form.

Keith

01.15.2010

Hi,

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.2010

Very nice!  Thank you

Julie

01.17.2010

Trevor, 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=&quot;checkbox&quotname=&quot;billShow&quotid=&quot;billShow&quotvalue=&quot;true&quot; />My billing address is different from my mailing address 

Thanks so much for all your help!
Julie

Julie

01.17.2010

Sorry.. 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.2010

hi,

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.2010

Trevor, 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.2010

I want to thank you too, your method is really great, already use it on my blog. Great post, great contact form.

Julie

01.18.2010

Trevor, 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.2010

I’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.2010

sorry.. :)

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.2010

thank you very much, it’s awesome tutorial

ven

02.01.2010

i 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.2010

ok . now all my pages are redirecting to static home page. i think this is related with wordpress settings.

ciprian

02.03.2010

Wow 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.2010

No 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.2010

Great 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.2010

here 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.2010

Awesome 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.2010

Yeah, 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.2010

Trevor,

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.2010

Have 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.2010

Firstly, 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.2010

I 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=&quot;text/javascript&quotsrc=&quot;/scripts/jquery.js">
<script type=&quot;text/javascript&quot; src=&quot;/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.2010

Trev,

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.2010

Remember 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.2010

Thanks 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.2010

Thanks 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.2010

Hello 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.2010

Okaay, 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.2010

Thanks 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.2010

By 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.2010

Hey 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.2010

heh 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.2010

Hi, 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
&iacute;a
 Biomagnetismo
 Abrir un Centro de Distribuci
&oacute;

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.2010

I 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
&iacute;a
 Biomagnetismo
 Abrir un Centro de Distribuci
&oacute;

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.2010

Thank 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.2010

Looks 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.2010

Hi Trev,

How to configure a Local Email Server?

Thank you

Donald Jenkins

03.07.2010

I 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.2010

Hi 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.2010

Hell 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.2010

Hi, 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.2010

Trevor:

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

04.09.2010

@Trevor-
Thanks. I should have been able to figure that out.

Ludz

04.14.2010

This 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.2010

Hi 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.2010

Hi
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.2010

I 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.2010

I got it to send on WP 3.0 once but only when I checked the send me a copy box?

nBall

05.18.2010

Trevor, 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.2010

Hi @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.2010

Hi 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.2010

Hey 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.2010

Hey 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.2010

Thanks a lot! I was having trouble preparing a decent contact from. This really helped me a lot.

Steve

06.23.2010

I 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.2010

Great solution to a common problem

Will Dawson

07.01.2010

Hey 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.2010

Really a great tutorial and a great commenting system implemented on this site..

kilinkis

07.28.2010

thx dude, very useful

Jacob

08.09.2010

Hey, 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.

njp

11.01.2010

Thanks for a great tutorial. Quick question: how would I add an “onchange” event handler to a field? I would like to update a total based on some numbers that the users enters into text fields.

Trevor

11.01.2010

@njp-
You can use the jQuery change() method.

Keevan

11.03.2010

Very very interresting, thank you so much !

Too many plugin kill the plugin.

SK

11.23.2010

Hey Trevor,
Had a quick question. I used your tutorial to come up with my own contact form and it works beautifully. No bloated plugins! However, I’m now using the same idea to build a “Email This Article” sidebar widget. However, I need a bit of help.

I have the form that requests a person’s email and destination email on the the sidebar of every single.php page. When someone submits the form, they get a popup with re-captcha to verify the send, to prevent spam. However my question is this.

The php file I’m posting to is simply named email-this.php and resides in my WP templates directory. Is there away to add a .htaccess or php command to make it work so that the form can get posted to example.com/email-this/ instead of a long url all the way into wp-content/themes/my-theme/email-this.php.

Also, the data about the article is posted to this php file. I don’t want people to be able to access this file directly either. Anyway of solving that?

Please let me know if you have any suggestions. Thanks!

Trevor

11.24.2010

@SK-
You should be able to use an .htaccess rule to rewrite that URL. There are tons of guides out there.

You can disable direct access by using something like this:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>

Michael

12.01.2010

Thank you very much for breaking this down so elegantly. Been working on this all night - but this is a beautiful solution ;-)

SK

12.01.2010

Just wanted to say thanks for the .htacces rewrite tip. I have both a contact form and an “email this” tool built on your concept!

Shannon

12.09.2010

Thank you so much for the great contact form. Works like a charm. I love the honeypot captcha - one thing most of the form plugins are missing.

Mutahhar Mustafa

12.12.2010

Thanks for this… But i am facing a bit of difficulty actually in recieving…. The mail never gets to the email address i give instead of .(JavaScript must be enabled to view this email address) ... The email i am sending to is a Gmail account but i just can’t recieve it !

Trevor

12.12.2010

@Mutahhar Mustafa-
It really depends on how your server is setup. Did you update the email address in the code?

J v. T

12.14.2010

Hi Trevor.

The form is not sending any mail.
! = there is no mail server on this server. Is VPS and no mail server was setup.
Just using gmail directly. Sending email via smtp is working like charm. With SMTP plugin. WP. So any form will work as plugin. [ This solution is used in fact on other sites ]
But not your form sadly. No error message, rien!

Suspect : need to implement gmail smtp into form?
Or somehow include SMTP plugin config into.

Any suggestion?

PS. great form and clean site. Thank you.

Trevor

12.14.2010

@J v. T-
You will have to modify the form so that it works with the SMTP plugin config.

Risco.

01.05.2011

Trevor,

your form works fine for me, thanks a lot.

I only have this little issue: while visualizing the contact-form page, Firefox reports me a Js error, says:

$ is not defined

that comes from the very first line of contact-form.js

Is it normal? Or did I compromitted something?

Thank you again,

Risco.

Trevor

01.09.2011

@Risco-
Looks like jQuery was removed from the demo page. I’ve added it back to the demo so it should work now. Thanks for letting me know.

Risco.

01.12.2011

Trevor,

no… thanks to you!

I’ve downloaded again your source files, and I overwrited the both contact-form.js and jquery.js files in my ftp with the ‘new’ ones.

But I see the same result… did I do the wrong thing? =)

Trevor

01.13.2011

@Risco-
Do you have a link to the page?

Risco.

01.15.2011

Yessss

yes, I added my link… well it is only a WORK IN PROGRESS =)

In the ‘send a message’ page, you can check the issue (I use to turn on the Firefox web developer toolbar to check it).

R.

Trevor

01.15.2011

@Risco-
The JavaScript that I wrote will not work if you don’t have jQuery included.

Risco.

01.16.2011

Trevor… =(

well… I think there is a misunderstanding (maybe because I’m not english mothertongue, and also ‘cause I’m a very very basic user of javascript and arond, I’m sorry). I’ll try again from zero.

1: It works. I did put your script in my website (all the files) and it works. So I correctly receive the emails that I send from my website.

2: althoug, the trouble is this: when just the contact-form page opens in the browser (also before the user intercacts with anything in the page) the browser reports me the ‘$ is not defined’ error. It happens again when the user click on the ‘send’ button.

Thanks again…

Trevor

01.16.2011

@Risco-
You need to include jQuery on your page.

Risco.

01.17.2011

@ Trevor.

Wooops… I did not upload the new header.php with the script in head =)
Now I’ve done, and I also updated jQuery with the newest version.

Well it is really crazy but the script no longer works: for example now it does not check for the email or message fields if are correctly edited, and he sends anyway the message.

 

Trevor

01.17.2011

@Risco-
If you are having so much trouble working with this script, maybe you should consider just using a plugin.

Risco.

01.17.2011

No, it works.

Insisting on jQuery has confused my (very odd…) ideas. But apart from this strange detail, thanks a lot Trevor, your script is the best I founded in web.

Oh yeah.

yashmistrey

01.26.2011

hey i have issue ! i am using this contact form but iam using smtp , php mail function not working on my site so how to add smtp class / mailer to run this contact form smoothly ! i am using smtp plugin ‘WP-Mail-SMTP ’ by Callum Macdonald

please reply as this is very important for me ! i was searching for solution !

Trevor

01.26.2011

@yashmistrey-
A quick Google found a found a bunch of results that should help you.

Steve

01.26.2011

Hi trevor, I sent a message but apparently this wasn’t added to the article.

Here I go again, thanks for the tutorial the best found through google.
I wanted to ask you a little question if It sounds obvious I’m sorry, I’m just starting in this path. I’d like to know how your form actually sends the mail since I don’t see any smtp server configuration setup in your code, or a php class like phpmailer to allow you to send emails.

Is it a function built in php that allows to email to accounts without the need for a php class or a smtp server from your hosting?

and do you think this form would actually send the email if I set it up in a local enviorment like wamp connected to the internet, would it reach the email account or this has to be on a server to work?

Trevor

01.26.2011

@Steve-
It is sending mail through the built in mail() function. If you set your local environment up correctly, it will work fine.

Christian K. N.

02.08.2011

Hi, Trevor.

Thanks for the great tutorial and code. I’m putting it to use on an idea I’ve been toying with.

I have combined your code with some custom fields and a custom write panel. Now, my post author can tick a box to include a contact form in any post or page, and add a title to that contact form. (E.g.: “Yes, I would like to learn more about contact forms!”)

I’m not learning php as quickly as I’d hoped, however, and I can’t figure out how to get the last piece of the puzzle into place without breaking the code: Including the value of the custom field (the form title) in the e-mail that is sent, so I can tell what the sender is replying to. (Alternatively including the post’s title or permalink, but that wouldn’t be quite as elegant. :-)

I can see that you get (too) many questions and support requests about this contact form, though, and realize that you don’t have time to solve every problem people create for themselves (you), but any help or hint you can give will be greatly appreciated.

Trevor

02.08.2011

@Christian K. N.-
The easiest thing would be to use a hidden form field:

<input type="hidden" name="form_title" id="form_title" value="<?= $custom_field ?>" >

Then in the part processing the form, just grab the $_POST[‘form_title’].

ashfaq ahmed

02.11.2011

please help me how to add multiple file to upload and send multiple these file into mail.Anyone know please help me i am very thankx full to you.
waiting for your replay

Trevor

02.11.2011

@ashfaq ahmed-
Handing files via AJAX is kind of a pain in the butt. I probably wouldn’t recommend it.

skinnyboy

02.12.2011

thank you very much for your trouble
i couldn’t get to the end of the comments(too tired), so excuse me if you have answered this before (and ignore me, no hard feelings :)  )

how can i have my contact script not be self referencing??
i really don’t like the idea, (from a programming perspective) and i cant find any tuts online. Only similar to yours , with the self referencing.

No matter where i place the contactFormScript in the WP folders, it simply cant be found.. (testing locally on xampp)

thank you in advance

Trevor

02.14.2011

@skinnyboy-
You can just pull the part that processes the form into another page template. Then create two different templates and change the action for the form.

skinnyboy

02.14.2011

@trevor
i get the part of changing the form action (naturally)
i get the part of pulling the form processing code into a separate php file (i.e. formProcessingScript.php)

i am guessing you are suggesting creating one more page template (the one that will include/or make use of the form processing code) and not two, right?

and then wp will be able to find the page with the appropriate template even if there is no page created with the corresponding template, to process the form? it will find it using the template hierarchy right?

i will try that as soon as i get some time
thank you again for your time and advice

Trevor

02.14.2011

@skinnyboy-
Two form page templates: one to display the form, and another to process the form. You will have to create a page for both.

skinnyboy

02.14.2011

I probably didn’t make myself clear sorry for that
yes, this is what i meant, i said one more page template since you (and i can just copy) have provided the code for the form displaying one

i won’t say thank you again, but this:
fast respond!!! couple of machs for sure

Russell Gillman

02.15.2011

Hi, any idea how to fully integrate a basic telephone number field to this? I’ve got the non-javascript validation working on telephone field, but can’t seem to get it working with jquery. I’d have thought it was a simple as adding a few lines to contact-form.js:

} else if($(this).hasClass(‘telephone’)) {

etc… but it doesn’t want to know. Please help! Thanks :-)

Trevor

02.15.2011

@Russell Gillman-
Looks like you are going down the right path. What isn’t working?

Russell

02.15.2011

@Trevor

Thanks for the reply. The thing that isn’t working is the jquery validation of the new telephone number field. It recognises an empty field, but I want the javascript to check that the telephone input is in the correct format (ie only numbers), and if not, ask for a correct input.

Basically, I’ve just added this code below the existing ‘else if email’ code:


} else if($(this).hasClass(‘telephone’)) {
  var telephoneReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  if(!telephoneReg.test(jQuery.trim($(this).val()))) {
    var labelText = $(this).prev(‘label’).text();
    $(this).parent().append(’<span class=“error”>Please enter a valid ‘+labelText+’</span>’);
    hasError = true;
  }
  }

I’ve obviously added a new <li> to the main code, so that’s not the problem. I’ve even gone backwards and amended the existing ‘email’ check to test it—replacing any instance of ‘email’ in the code of all related files to ‘telephone’ just to test the code. For some reason this seems to break it (and I’ve been very careful to change every one), but I see no reason why? Hope someone can help! :-)

Russell

02.15.2011

BTW - I realise that the code above is still checking for the email address format–not got to this bit yet! Either way, I can type anything into the new field (ie not formatted as an email address) and it doesn’t recognise it as incorrectly formatted.

Trevor

02.16.2011

@Russell-
And you added the telephone class to the input? Do you have a link to the form?

Russell

02.16.2011

@Trevor
As in this (in contact-form.php)?

<li><label for=“telephone”>Telephone</label>
<input type=“text” name=“telephone” id=“telephone” value=”<?php if(isset($_POST[‘telephone’]))  echo $_POST[‘telephone’];?>” class=“telephone” />
<?php if($telephoneError != ‘’) { ?>
<span class=“error”><?=$telephoneError;?></span>
<?php } ?>
</li>

Will post a link shortly.

Trevor

02.16.2011

@Russell-
I guess I’ll be able to test better when you post a link. I don’t really know what kind of problem you are experiencing.

Russell

02.16.2011

@Trevor
Problem solved. I just had one too many curly brackets! Grrrrr :-)
Thanks - great script.

Matthew Hull

02.18.2011

This is a great script, and I have used it a few times.
I want to know, is it possible to send a thank you for your email/thank you for signing up email to the person who submits the form?

How would I do this?

Trevor

02.18.2011

@Matthew Hull-
It’s already setup to work like that. If the person checks the checkbox, it sends them a copy.

Matthew Hull

02.18.2011

Hi Trevor, Is there a way to make it automatically send a thank you email?
e.g ‘Thank you for for your email’

Trevor

02.18.2011

@Matthew Hull-
Just remove the checkbox and the conditional around the second mailing.

Matthew Hull

02.21.2011

Hi trevor, how would I remove the conditional around the second mailing?

What would I change the following to?

if($sendCopy == true) {
  $subject = ‘You emailed Your Name’;
  $headers = ‘From: Your Name <noreply@somedomain.com>’;
  mail($email, $subject, $body, $headers);
  }

Trevor

02.21.2011

@Matthew Hull-
$subject = ‘You emailed Your Name’;
$headers = ‘From: Your Name <noreply@somedomain.com>’;
mail($email, $subject, $body, $headers);

Joanne

02.21.2011

I love the form and I am trying to use it on a blog I am creating. I have managed to get the form validating with the error text appearing in red, but I really want the fields to turn red to highlight them more, I have tried the suggestion you gave to Olli (03.08.2009) but I can not get it to work.

I changed that part of the javascript, I have added in the css style with the inputError and tried various css styles and cannot get it to work.

Any suggestions?

Trevor

02.21.2011

@Joanne-
Do you have a link to your page?

Trevor

02.21.2011

@Joanne-
That link asks me to login.

Joanne

02.21.2011

oh sorry completely forgot, the company put it on to stop the site going live. Is there another way I can show you?

Trevor

02.21.2011

@Joanne-
Not sure, you tell me if there is any other way you can show me.

Joanne

03.02.2011

Hi

The issue was the email validation, for some reason it would not work. i changed it to:           
var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;


I got your form to work and I have the text and also the fields now flagging up in red, but I wondered if there was a way that when you click back into the error field, it removes the error class and reverts back to white with no error text on that field. I have put in:     

if(!hasError) {
          $(this).removeClass(‘inputError’);
        }
      });

so when you click in it removes the colour/text but as soon as you click away it reverts back to red.

any help would be great.

Trevor

03.02.2011

@Joanne-
Sure, just remove the class on focus:

$(this).focus(function() {
  $(this).removeClass('inputError');
});

That is assuming that this is your input.

Joanne

03.02.2011

Thanks that worked on the fields, but I still have the “Please fill out the required field” text appearing, is there a way to remove this.

Also, is there a way the email can stay error-ed until and actual email address is submitted, I’ve seen this on jquery validation

Trevor

03.02.2011

@Joanne-
Just traverse up the DOM and remove the error element when you focus on the input.

If you need the email to stay error-ed out, you would need to bind an event to keydown (or a similar event) to constantly check to see if the email address if valid as a key is pressed.

Tony

03.11.2011

Hello Trevor,
Thank you so much for this tutorial.
I’m experimenting with your code and ideas and enjoying every bit of it. However, since I’m still at basic level I was unable to get the phone field that I added right underneath email field.

Added phone field (it is not a required filed) is visible in form. When I receive the email I see Phone: filed but the data entered is not there in front of Phone:

The code I added to the form area is:
<li><label for=“phone”>Phone</label>
  <input type=“text” name=“phone” id=“phone” value=”<?php if(isset($_POST[‘phone’]))  echo $_POST[‘phone’];?>” />
</li>

and I also added the below before calling the header:
  //Check to make sure that the phone field is not empty
  if(trim($_POST[‘phone’]) === ‘’) {
  $name = trim($_POST[‘phone’]);
  }

(maybe this bit is not necessary)

1. It would be really great if you could teach us how to add a field (not required) such as Phone:

2. Also if you have time, please teach how to add a simple drop down field (required) such as what fruit you like: Apple,Orange,Tomato(in drop down)

3. If it’s not too much, please teach how make a field required and not required.

I think this will complete my form that I’m trying to implement in my website.
Thank you so much once again for your simple form.

Trevor

03.11.2011

@Tony-
1. You’ve got everything right, except you said phone should not be required, but you want to modify this a bit:

if(trim($_POST[‘phone’]) !== ‘’) {
  $phone = trim($_POST[‘phone’]);
}

2. Select elements work exactly the same as an input, there can just be an unlimited number of possible values.

3. If you want a field to be required, then you want to do this:

$hasError = true;

That is what triggers the form to know that there are errors in the form.

Tony

03.11.2011

@Trevor
I want to say I love you Trevor. But if it’s too much or inappropriate, many thanks. Your answers worked magic and thanks to you my form is complete now.

I have two more problems but I can live with them.

1. email goes to spam when using gmail even when I say it’s not spam. Maybe it’ll work fine if I move it to inbox once again.

2. I receive an error when I use the following code to check phone number against regular expressions. If you can spot anything by looking at it please let me know what’s wrong.

  //Check to make sure that a valid phone field is not empty
  if (!eregi(”^\d*[0-9](|-\d*[0-9]|,\d*[0-9])?$”, trim($_POST[‘phone’]))) {
  $phoneError = ‘You entered an invalid phone number.’;
  $hasError = true;

  }  else if(trim($_POST[‘phone’]) !== ‘’) {
  $phone = trim($_POST[‘phone’]);
  }

I can’t thank you enough. All the best.

Trevor

03.11.2011

@Tony-

1. I guess it depends on the subject and email address you are sending from.

2. Not sure, I’m not the greatest with regular expressions. I’m sure you could Google around to find the solution.

Tony

03.13.2011

@Trevor..
I’m sure I can work something out. Thank you for all your help.

Tony

03.15.2011

Hello again Trevor,

Is it possible to add styles to received form details when using your form.

Thanks.

Trevor

03.15.2011

@Tony-
I’m not sure what you mean.

Tony

03.15.2011

@Trevor

Can I add some background color and make field names bold in received email?
Thanks.

Trevor

03.15.2011

@Tony-
In the actual email? You can turn it into an HTML email and do whatever you want. You just have to send the correct headers in the mail function.

Tony

03.15.2011

@Trevor
We are on the same page. Yes the actual email.
Say that I would like to see Email:  in bold when I receive the actual email. So what I did was this.. (simply added the html starting and ending tags)
$emailTo = ‘me@somedomain.com’;
$subject = ‘Contact Form Submission from ‘.$name;
$sendCopy = trim($_POST[‘sendCopy’]);
$body = “Name: $name \n\nEmail: $email \n\nComments: $comments”;
$headers = ‘From: My Site <’.$emailTo.’>’ . “\r\n” . ‘Reply-To: ’ . $email;

But are you suggesting that I should attach a css file to the header?

Also, do I need to get the help of (must use) class.phpmailer.php to attach a file through the form?

Thanks.

Trevor

03.15.2011

@Tony-
Check out the link that I posted. It gives examples about doing HTML emails. You will have to use something else to send attached files unless you are uploading them to the server.

Tony

03.15.2011

@Trevor
I’ll try them out. Thanks for the guidance.

R.w

03.15.2011

Cool script but the honeypot isn’t preventing me from sending the form whether I put anything in the empty field or not. Am I missing something?

Trevor

03.15.2011

@R.w-
That validation is only on the PHP side in the demo. You could easily add it to the JS too.

R.w

03.15.2011

thanks Trevor, is it included in the source files? btw, does it have a gibberish filter also?

Trevor

03.15.2011

@R.w-
Yes, everything should be in the source files. I’m not sure what you mean about the gibberish filter.

R.w

03.15.2011

something like this…

if($gibberish_check)
{

$vowels = array(‘a’,‘e’,‘i’,‘o’,‘u’);

$consonants = array(‘b’,‘c’,‘d’,‘f’,‘g’,‘h’,‘j’,‘k’,‘l’,‘m’,‘n’,‘p’,‘q’,‘r’,‘s’,‘t’,‘v’,‘w’,‘x’,‘y’,‘z’);

function recursive_array_gibberish_check($element_value)
{

global $set;
global $vowels;
global $consonants;
global $return_value;
global $gibberish_threshold;

$consecutive_consonant_count = 0;
$consecutive_vowel_count = 0;

if(!is_array($element_value))
{

$exploded_value = explode(” “,$element_value);

foreach($exploded_value as $word_to_check)
{

if((strlen($word_to_check) >= $gibberish_threshold) && (!is_numeric($word_to_check)))
{

Trevor

03.15.2011

@R.w-
No, but you can add whatever you would want to add.

kućni ljubimci

03.16.2011

Thanks for shareing!!!

Tom

03.16.2011

Hi and Thanks a lot for this excellent tutorial.

I haven’t found a tutorial as good as this one. I’ve been searching for hours :) .

My question is :

What license is this code under? Is it GPL? can it be used in a commercial theme.

Thanks!!

Trevor

03.16.2011

@Tom-
Sure, feel free to use it. It would be nice to reference where the script came from.

Tom

03.16.2011

@Trevor

Thank you !!
I will for sure.

thanks!

Lance

03.21.2011

This will not show up on my template section of the page. I only get default theme

Trevor

03.21.2011

@Lance-
Did you make sure to add the comment at the top to define the template name?

Karan Israni

03.23.2011

Hi,

Great tutorial there. I did everything as you said and am up and running, but for one problem. When i click on ‘EMAIL ME’, the mail is not sent.

I have changed the ‘to’ and ‘from’ email address but still no luck.

//If there is no error, send the email
  if(!isset($hasError)) {

$emailTo = ‘karan_israni@hotmail.com’;
  $subject = ‘Contact Form Submission from ‘.$name;
  $sendCopy = trim($_POST[‘sendCopy’]);
 
$body = “Name: $name \n\nEmail: $email \n\nComments: $comments”;
  $headers = ‘From: My Site <’.$emailTo.’>’ . “\r\n” . ‘Reply-To: ’ . $email;
 
mail($emailTo, $subject, $body, $headers);

  if($sendCopy == true) {
  $subject = ‘You emailed Your Name’;
  $headers =

‘From: Your Name <israni.karan@gmail.com>’;
  mail($email, $subject, $body, $headers);
  }

  $emailSent = true;

}
}
} ?>

Apart from the email ids, i haven’t made any other changes.

I am making a wordpress theme, my first ever, and i want to use this form as a template there. I am testing in Xampp.

I would like it if i could make an option for this in my theme option page where user will enter email id and mail will be sent to that id. This means, to change email id, no need to edit template files. Just change in theme options page. Possible?

P.S. This comment form here is awesome. How do i get such a form? You using a plugin or coded it yourself?

Thanks.

Trevor

03.23.2011

@Karan Israni-
There are way too many variables in mail server setups to try and guess. Can you create a template on the server that just uses the mail() function on page load?

I’m sure that you could use options to handle the email address. Although the whole point of this was to not use a plugin.

My comment form is coded from scratch for ExpressionEngine.

Karan Israni

03.24.2011

“There are way too many variables in mail server setups to try and guess. Can you create a template on the server that just uses the mail() function on page load?”

I didn’t get you. I’m using Xampp and testing everything in my local environment.

“I’m sure that you could use options to handle the email address. Although the whole point of this was to not use a plugin.”

‘Tis true but i will be making my theme available for download for everyone so if i make a theme usable by anyone, i just HAVE to make it this way, right? Otherwise noobs won’t be able to figure out and the contact form will be useless.

“My comment form is coded from scratch for ExpressionEngine.”

Have you written any tutorial for this? If not, then are you planning to? I’m very impressed with this form and would love to inherit it in my theme.

Thanks for your time.

Trevor

03.24.2011

@Karan Israni-
“I didn’t get you. I’m using Xampp and testing everything in my local environment.”

Has mail ever worked? If you create a PHP file and use the mail() function, does it send?

“‘Tis true but i will be making my theme available for download for everyone so if i make a theme usable by anyone, i just HAVE to make it this way, right? Otherwise noobs won’t be able to figure out and the contact form will be useless.”

Or you can just pull the bloginfo(‘admin_email’).

“Have you written any tutorial for this? If not, then are you planning to? I’m very impressed with this form and would love to inherit it in my theme.”

Nope, and don’t plan to. This is an EE comment form, the backend won’t work with WP. The frontend is all available in the source of the page.

Tony

03.24.2011

Hello again Trevor,
So far everything is working perfectly and thank you for walking me this far.

One question though. I’m not using the .js file for validation as I’m happy with php validation included in your code.

1. Is there any disadvantage?

2. When using php validation only, Is there a way to display the from part of the page on the screen whenever an error (There was an error submitting form) occurs at submission. Because if contact page contains a lot of content just above the form, at error on submission, it’ll go to the top of the page and those error messages and the form is way down the page were it won’t be appearing in the visible part of the screen (must scroll down to the page where the form is). This doesn’t happen on successful submission as success message appear on top part of the page.

Thanks.
Thanks.

Trevor

03.24.2011

@Tony-
1. Just a different user experience. You are adding hits to the server instead of doing client-side.

2. Not sure exactly what you mean. You could use a hash link to scroll down the page.

Tony

03.26.2011

@Trevor
Thanks you. Both answers answered my questions.

Karan Israni

03.26.2011

“Or you can just pull the bloginfo(‘admin_email’).”

Hi, could you please tell me how to use this?
This option seems like a much better one than creating a themes option page for contact form.

Does the code <?php bloginfo(‘admin_email’); ?> go into the contact form’s php file and into the ‘to’ field? Like this:

//If there is no error, send the email
  if(!isset($hasError)) {

$emailTo = ‘<?php bloginfo(‘admin_email’); ?>’;
  $subject = ‘Contact Form Submission from ‘.$name;
  $sendCopy = trim($_POST[‘sendCopy’]);
 
$body = “Name: $name \n\nEmail: $email \n\nComments: $comments”;
  $headers = ‘From: My Site <’.$emailTo.’>’ . “\r\n” . ‘Reply-To: ’ . $email;
 
mail($emailTo, $subject, $body, $headers);

  if($sendCopy == true) {
  $subject = ‘You emailed Your Name’;
  $headers =

‘From: Your Name <israni.karan@gmail.com>’;
  mail($email, $subject, $body, $headers);
  }

  $emailSent = true;

}
}
} ?>

?

Trevor

03.26.2011

@Karan Israni-
Yes. You can see more in the documentation.

Aziz

04.06.2011

Great tutorial Trevor. I think im going to implement this on my site. Its really simple and straightforward. I wanted to know what your take is on phpmailer or swift mailer? Do they add any additional security measures instead of the stock php mail() function?

Much appreciated.

Trevor

04.06.2011

@Aziz-
Sorry, I can’t give you any feedback on that; I have no idea.

Tony

04.10.2011

Hello again Trevor,

Your form’s textarea field contains “stripslashes” function and it removes linebreaks as well.

What can you suggest to keep linebreaks intact when the data is entered in to the textarea as few paragraphs?

Thank you.

Tony

04.10.2011

Sorted it but thanks for having a look.

I simply used nl2br function and so this is how it was done.

$comments = nl2br(stripslashes(trim($_POST[‘comments’])));

Thank you.

Sander

04.14.2011

Heey,

the e-mail doesnt get send when Javascript is enabled. I cant find the problem.

http://www.sanderwehkamp.nl/assignments/site

Trevor

04.14.2011

@Sander-
Looks like you’ve got a syntax error when you submit the form. I think it might have something to do with the regular expression.

Max Rose-Collins

04.30.2011

Very nice tutorial, very well explained!

Thanks for your help.

I will defiantly be implementing this on my website, so much easier to customise than a plug in and the code is a lot cleaner.

Excellent post

Max Rose-Collins

Matt

05.04.2011

Hi, I am using a simplified version of this on a site as a newsletter form to collect first, last and email address. The only problem is that there has been some spam getting through with fake email addresses. Is there any Spam blocker script/ Captcha script that could possibly be added to this to block the spam?

Many Thanks,

Trevor

05.04.2011

@Matt-
There are tons of captcha scripts available online, and this article is over 2 years old, so I don’t think I’ll be updating this.

So if the captcha field was left blank, we will continue to validate

Too late, comments are closed!

Don’t worry, you can email me or contact me on Twitter.