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">&nbsp;</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">&nbsp;</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.