Well as the title says we are going to build a contact page in this tutorial. Nothing fancy, just the main stuff like:
- PHP validation
- jQuery validation
- AJAX submission (if javascript is turned off it will be submitted normally)
We’re going to use WordPress custom template for this. Ready to get started? Just so you know, if you encounter any problems following this steps feel free to ask me about resolving them using the comment form and i’ll do my best to help you out.
Step 1 – Creating the template
First of all we need to create a custom template for our contact page. Simply create a new file in the theme folder, name it template-contact.php and add the code bellow.
<?php /* Template Name: Contact Form */ ?>
Now open up page.php file from your theme and copy the whole content after the code we just added. You should end up with something similar to the code bellow.
<?php /* Template Name: Contact Form */ ?> <?php get_header(); ?> <div id="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post" id="post-<?php the_ID(); ?>"> <h2><?php the_title(); ?></h2> <div class="entry"> <?php the_content(); ?> </div> </div> <?php endwhile; endif; ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
If you have more content then that don’t worry, it depends on the theme you’re currently using. If you are familiar with coding a WordPress theme then you can remove the comments part, but it’s not really necessary because you can disable commenting from inside the admin panel.
Now, if you take a look at the code bellow you will see where the rest of the code will go (the commented green colored parts)
<?php /* Template Name: Contact Form */ ?> <!-- PHP PART 1 GOES HERE (PROCESSING) --> <?php get_header(); ?> <!-- jQuery GOES HERE (VALIDATION AND AJAX PROCESSING) --> <div id="main"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post" id="post-<?php the_ID(); ?>"> <h2><?php the_title(); ?></h2> <div class="entry"> <?php the_content(); ?> </div> </div> <?php endwhile; endif; ?> <!-- CONTACT FORM HTML AND PHP PART 2 (MESSAGES) GOES HERE --> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
Step 2 – HTML
In this step we will create the form, just copy the snippet bellow in the place for the HTML part (as shown in the part 1).
<div id="contact-form">
<form action="<?php the_permalink(); ?>" id="contact-form" method="post">
<p><label for="c_name"><?php _e('Name') ?></label> <input type="text" name="c_name" id="c_name" /></p>
<p><label for="c_email"><?php _e('Email') ?></label> <input type="text" name="c_email" id="c_email" /></p>
<p><label for="c_subject"><?php _e('Subject') ?></label> <input type="text" name="c_subject" id="c_subject" /></p>
<p><label for="c_message"><?php _e('Message') ?></label> <textarea name="c_message" id="c_message"></textarea></p>
<p><label for="c_submit"> </label> <input type="submit" name="c_submit" id="c_submit" /></p>
<input type="hidden" name="c_submitted" id="c_submitted" value="true" />
</form>
</div>
If you’re confused about where exactly to put it, then simply place it after the “loop” (<?php endwhile; endif; ?>), it’s important that it is in the same div as the div with class “post”.
Step 3 – CSS
We made the form, but it’s not really good looking so let’s add some simple styling. I commented some of the lines so it should be easy to understand what’s what.
Notice: The CSS goes in the style.css file, not inside the new template we created.
#contact-form label {
display:block; /* needed in order to set a width */
float:left; /* make it inline with the input field */
width:100px;
}
#contact-form textarea {
width:300px;
height:80px;
}
#contact-form .error {
margin-left:100px; /* same as label width */
color: #9e2828;
}
Now it looks better, let’s move on.
Step 4 – PHP
The first chunk of code goes before the “<?php get_header(); ?>”.
<?php
$name_error = '';
$email_error = '';
$subject_error = '';
$message_error = '';
if($_REQUEST['c_submitted']){
//check name
if(trim($_REQUEST['c_name'] == "")){
//it's empty
$name_error = __('You forgot to fill in your name');
$error = true;
}else{
//its ok
$c_name = trim($_REQUEST['c_name']);
}
//check email
if(trim($_REQUEST['c_email'] === "")){
//it's empty
$email_error = __('Your forgot to fill in your email address');
$error = true;
}else if(!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_REQUEST['c_email']))){
//it's wrong format
$email_error = __('Wrong email format');
$error = true;
}else{
//it's ok
$c_email = trim($_REQUEST['c_email']);
}
//check name
if(trim($_REQUEST['c_subject'] === "")){
//it's empty
$subject_error = __('You forgot to fill in the subject');
$error = true;
}else{
//it's ok
$c_subject = trim($_REQUEST['c_subject']);
}
//check name
if(trim($_REQUEST['c_message'] === "")){
//it's empty
$message_error = __('You forgot to fill in your name');
$error = true;
}else{
//it's ok
$c_message = trim($_REQUEST['c_message']);
}
//if no errors occured
if($error != true) {
$email_to = "your_email_here@gmail.com"; //change this with your email address
$message_body = "Name: $c_name \n\nEmail: $c_email \n\nComments: $c_message";
$headers = "From".get_bloginfo('title').' <'.$emailTo.'>' . "\r\n" .'Reply-To' . $email;
mail($email_to, $c_subject, $message_body, $headers);
$email_sent = true;
}
}
?>
It’s a big chunk of code but it’s really simple, first we validate the submitted data by checking if it’s empty and is the email correct. If it is empty or the email isn’t in the right format we set the “error” variable to true and the error messages so after finishing with the validation we can know what to do and let the user know too, submit or not. If the error variable is not set to true then we process with the emailing and if everything goes well we set up another variable, email_sent, to true so we know that the email is sent.
Don’t forget to change the $email_to variable to your email address.
In the second part of the PHP we are going to show the user if everything is correct, and if it’s not let him know what’s wrong. The new codes are mixing up with the previous coding so let’s take it slowly.
First of all when the contact email is successfully sent we don’t want to show the contact form, right?
<?php if(isset($email_sent) && $email_sent == true){ ?>
<p class="email-sent"><?php _e('Thank you for contacting. I will answer your email as soon as possible.') ?></p>
<?php }else{ ?>
<div id="contact-form">
<!-- the contact form -->
</div>
<?php } ?>
Using a simple if/else check we are either gonna show the message for the successful contact or the contact form. The part inside the }else{ and } is the contact form HTML, nothing new.
Now, it’s time for adding the code that show the error messages if something isn’t filled in right. After every paragraph (<p>content</p>) we will check if the error variables are not empty and if they aren’t then echo that error. This is how it looks after all the fields are updated.
<p><label for="c_name"><?php _e('Name') ?></label> <input type="text" name="c_name" id="c_name" /></p>
<?php if($name_error != '') { ?>
<p class="error"><?php echo $name_error;?></p>
<?php } ?>
<p><label for="c_email"><?php _e('Email') ?></label> <input type="text" name="c_email" id="c_email" /></p>
<?php if($email_error != '') { ?>
<p class="error"><?php echo $email_error;?></p>
<?php } ?>
<p><label for="c_subject"><?php _e('Subject') ?></label> <input type="text" name="c_subject" id="c_subject" /></p>
<?php if($subject_error != '') { ?>
<p class="error"><?php echo $subject_error;?></p>
<?php } ?>
<p><label for="c_message"><?php _e('Message') ?></label> <textarea name="c_message" id="c_message"></textarea></p>
<?php if($message_error != '') { ?>
<p class="error"><?php echo $message_error;?></p>
<?php } ?>
<p><label for="c_submit"> </label> <input type="submit" name="c_submit" id="c_submit" /></p>
That’s it. Hope i was clear enough about this part, let me know if you have any questions.
Step 5 – Validation and ajax submissions with jQuery
I made some comments inside the code to explain what’s what but if you don’t understand something feel free to ask.
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function(){
jQuery('#contact-form form').submit(function(e){
//prevent the normal processing
e.preventDefault();
//delete the errors (so we don't get duplicates ')
jQuery("#contact-form .error").remove();
//declaring and setting vars
var value, theID, empty_error, email_error, error, emailReg;
empty_error = '<p class="error">This field is required</p>';
email_error = '<p class="error">The email you entered is not valid</p>';
error = false;
emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
//validating
jQuery('#contact-form textarea, #contact-form input[type=text]').each(function(){
value = jQuery(this).val();
theID = jQuery(this).attr('id');
if(value == ''){
jQuery(this).parent().append('<p class="error">'+empty_error+'</p>');
error = true;
}
if(theID == 'c_email' && value != '' && !emailReg.test(value)){
jQuery(this).parent().append('<p class="error">'+email_error+'</p>');
error = true;
}
});
//send email and loaded message
if(error == false){
jQuery('#contact-form').load('<?php the_permalink(); ?> .email-sent', jQuery('#contact-form form').serialize());
}
});
});
//-->!]]>
</script>
Step 6 – Adding the page
Now when everything is coded let’s create the page, follow these steps:
- Go to the create new page in the admin panel
- On the right side, bellow the “publish” widget you should see “attributes” widget, in the template dropdown/selectbox choose “Contact Form”
- If you want to show some content before the contact form simply add it like when you add content for any other page/post.
- Hit publish and that’s it.
Notice
Have in mind that if you are building a plugin or theme for wide use then you should read more about internationalizing plugins and themes. That way it can be translated easily to more languages.
Final Words
We’re done. If you would also like this contact page to have javascript/jQuery validation and ajax processing then say so in the comments and i’ll update this tutorial.
Hope it was easy to follow this tutorial and if you liked it then follow wpCanyon on twitter or subscribe to the RSS feed, you don’t want to miss out on more cool tuts like this one, don’t you?
Visit the best themes marketplace with over 600 premium wordpress themes.













This looks a bit like a raw php contact page
. Can you make it more powerful with ajax? I think that will be great.
Haha sure, i’ll update the tutorial with javascript/jQuery validation and AJAX submission tomorrow.
Second the Ajax request. Still, this is very useful as is. I haven’t made a web site yet that didn’t need a contact form.
Thanks!
Ah, nice! The exact tutorial I was looking for! Thank you!
@kenduret – Will be updated in few hours
You’re welcome.
@Cosmin – You’re welcome. I’m glad to help
Post Updated
Added jQuery validation and ajax submission
Just the other day I was looking for a simple way to implement a contact form in WordPress without having to install and configure a robust plugin, and your tutorial came in handy. I have to make some remarks though:
a) On line 58 in the PHP code for step 4, instead of adding $c_message you add $c_comment, which is a variable you didn’t use throughout the code.
b) I think a good practice is to keep the values a user has entered in the form, even though they were not valid. For instance, what if the message, which arguably takes the most amount of time to write, is valid, but the e-mail address or name are not. The user ends up having to write the message once more, only this time he’s a bit more frustrated.
c) There is a WordPress function that retrieves admin’s email address [ get_option('admin_email'); ], thus eliminating the need for someone to remember to updated the code
I’m really grateful for your contribution to the community and hope you keep up the good work!
@Adrian – Glad this tutorial helped you.
a) Good catch
Fixed
Will update the post tomorrow.
b) Good idea, will update the post tomorrow with that.
c) Forgot about that
Thanks, i’m always happy to hear kind words and i have some nice tutorials coming on so stay tuned
Well written tutorial, thanks for that.
But I can’t quite get it to work.
In the processing part I had to change if($_REQUEST['c_submitted']) to if($_REQUEST['c_submit']) before it would process.
And I have to use wp_mail() instead of mail() to fire off the mail (probably a problem with my own host).
One thing I cant figure out tho is the jQuery validation. It just replaces the content of #contact-form with nothing. The mail does not get sent. Validation works tho. Any ideas?
@Urlich – Turn off javascript in your browser and test it again. That way it will process it normally (no ajax) and let me know what you see when you process the email (success message or errors or nothing).
Sorry for the delay. It works perfect without java script. Both validation and the email is sent
This is greate just what I needed, all that missing is for me to add an option panel for this in wordpress
Please how do I create a new file in the theme folder?
Am a little confused about this, thanks
Same as you create a new file in any other folder.