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

Getting Ready

You can see the working form on my site PHP Snippets. It is a site of mine, so don’t hesitate to grab the RSS feed and follow it on Twitter if you want.

Step 1: Creating the page template

The first step is to create a page template. To do so, copy the page.php code into a new file named page-contact.php.

We have to add a comment at the beginning of the contact.php file to make sure WordPress will treat the file as a page template. Here’s the code:

<?php
/*
Template Name: Contact
*/
?>

Your contact.php file should look like this:

<?php
/*
Template Name: Contact
*/
?>

<?php get_header() ?>

	<div id="container">
		<div id="content">
			<?php the_post() ?>
			<div id="post-<?php the_ID() ?>" class="post">
				<div class="entry-content">
				</div><!-- .entry-content ->
			</div><!-- .post-->
		</div><!-- #content -->
	</div><!-- #container -->

<?php get_sidebar() ?>
<?php get_footer() ?>

Step 2: Building the form

Now, we have to create a simple contact form. Simply paste the following code within the entry-content div.

<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
	<ul>
		<li>
			<label for="contactName">Name:</label>
			<input type="text" name="contactName" id="contactName" value="" />
		</li>
		<li>
			<label for="email">Email</label>
			<input type="text" name="email" id="email" value="" />
		</li>
		<li>
			<label for="commentsText">Message:</label>
			<textarea name="comments" id="commentsText" rows="20" cols="30"></textarea>
		</li>
		<li>
			<button type="submit">Send email</button>
		</li>
	</ul>
	<input type="hidden" name="submitted" id="submitted" value="true" />
</form>

Nothing hard with this pretty self-explanatory html code for our form. Note the input type=”hidden” I added on line 19: It will be used later to check if the form has been submitted.

Step 3: data processing and error handling

Our form looks pretty good, but right it is very useless because it does not send any email. What we have to do is to verify if the form has been submitted then verify if fields have been filled correctly.

If fields are correctly filled, we’ll get the blog admin email and send them the email. Otherwise, no email will be sent and errors will be displayed to the user.

Paste the following code between the Page Template declaration and the get_header() function:

<?php
if(isset($_POST['submitted'])) {
	if(trim($_POST['contactName']) === '') {
		$nameError = 'Please enter your name.';
		$hasError = true;
	} else {
		$name = trim($_POST['contactName']);
	}

	if(trim($_POST['email']) === '')  {
		$emailError = 'Please enter your email address.';
		$hasError = true;
	} else if (!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']);
	}

	if(trim($_POST['comments']) === '') {
		$commentError = 'Please enter a message.';
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['comments']));
		} else {
			$comments = trim($_POST['comments']);
		}
	}

	if(!isset($hasError)) {
		$emailTo = get_option('tz_email');
		if (!isset($emailTo) || ($emailTo == '') ){
			$emailTo = get_option('admin_email');
		}
		$subject = '[PHP Snippets] From '.$name;
		$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
		$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

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

} ?>

What I’ve done here was simply to make sure that the form has been submitted and filled correctly. If an error, such as an empty field or incorrect email address occurred, a message is returned and the form isn’t submitted.

Now we have to display error messages below the related field, for example “Please enter your name”. Below you’ll find the complete form page template that you can use “as it”.

<?php
/*
Template Name: Contact
*/
?>

<?php
if(isset($_POST['submitted'])) {
	if(trim($_POST['contactName']) === '') {
		$nameError = 'Please enter your name.';
		$hasError = true;
	} else {
		$name = trim($_POST['contactName']);
	}

	if(trim($_POST['email']) === '')  {
		$emailError = 'Please enter your email address.';
		$hasError = true;
	} else if (!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']);
	}

	if(trim($_POST['comments']) === '') {
		$commentError = 'Please enter a message.';
		$hasError = true;
	} else {
		if(function_exists('stripslashes')) {
			$comments = stripslashes(trim($_POST['comments']));
		} else {
			$comments = trim($_POST['comments']);
		}
	}

	if(!isset($hasError)) {
		$emailTo = get_option('tz_email');
		if (!isset($emailTo) || ($emailTo == '') ){
			$emailTo = get_option('admin_email');
		}
		$subject = '[PHP Snippets] From '.$name;
		$body = "Name: $name \n\nEmail: $email \n\nComments: $comments";
		$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

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

} ?>
<?php get_header(); ?>
	<div id="container">
		<div id="content">

			<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
			<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
				<h1 class="entry-title"><?php the_title(); ?></h1>
					<div class="entry-content">
						<?php if(isset($emailSent) && $emailSent == true) { ?>
							<div class="thanks">
								<p>Thanks, your email was sent successfully.</p>
							</div>
						<?php } else { ?>
							<?php the_content(); ?>
							<?php if(isset($hasError) || isset($captchaError)) { ?>
								<p class="error">Sorry, an error occured.<p>
							<?php } ?>

						<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
							<ul class="contactform">
							<li>
								<label for="contactName">Name:</label>
								<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="required requiredField" />
								<?php if($nameError != '') { ?>
									<span class="error"><?=$nameError;?></span>
								<?php } ?>
							</li>

							<li>
								<label for="email">Email</label>
								<input type="text" name="email" id="email" value="<?php if(isset($_POST['email']))  echo $_POST['email'];?>" class="required requiredField email" />
								<?php if($emailError != '') { ?>
									<span class="error"><?=$emailError;?></span>
								<?php } ?>
							</li>

							<li><label for="commentsText">Message:</label>
								<textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?></textarea>
								<?php if($commentError != '') { ?>
									<span class="error"><?=$commentError;?></span>
								<?php } ?>
							</li>

							<li>
								<input type="submit">Send email</input>
							</li>
						</ul>
						<input type="hidden" name="submitted" id="submitted" value="true" />
					</form>
				<?php } ?>
				</div><!-- .entry-content -->
			</div><!-- .post -->

				<?php endwhile; endif; ?>
		</div><!-- #content -->
	</div><!-- #container -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Step 4: Adding jQuery verification

Our form is now working perfectly. But we can enhance it by adding a client side verification. To do so, I’m going to use jQuery and the validate jQuery plugin. This plugin is great because it allows you to verify that a form has been filled correctly, quickly and easily.

The first thing to do is to download the validate plugin and upload it into your theme file (under a /js directory). Once done, paste the following into a new file:

$(document).ready(function(){
	$("#contactForm").validate();
});

Save it as verif.js in your /js directory.

Now we have to link the javascript files to our theme. Open your header.php file and paste the following within the <head> and </head> tags:

<?php if( is_page('contact') ){ ?>
	<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.validate.min.js"></script>
	<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script>
<?php }?>

Once done, your form will be validated on the client side by the jQuery validate plugin. How does it work? It simply picks form element which have the css class required and verifies if they’re filled correctly. If not, a message is displayed.
The plugin is powerful and you can do lots of things with it, however this isn’t the purpose of this article. Hope you enjoy your new WordPress form!

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

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

4 thoughts on “How to create a built-in contact form for your WordPress theme”

  1. http://skidki-bc.com/1/img7/tramadol+buy/2_tram.png

    TRAMADOL without rx medications
    order cheapest TRAMADOL in fontana
    cheap order rx TRAMADOL
    buying TRAMADOL in burbank
    get cheapest TRAMADOL in san buenaventura
    buying cheap TRAMADOL in detroit
    buying cheapest TRAMADOL in topeka
    order TRAMADOL for cash on delivery
    TRAMADOL online sale
    purchase cheapest TRAMADOL in ut
    order TRAMADOL in state of south carolina
    buy TRAMADOL in state of arizona
    get cheap TRAMADOL in ontario
    purchase TRAMADOL in columbia
    purchase not expensive fedex TRAMADOL
    TRAMADOL fed ex overnight
    cheap TRAMADOL in state of north carolina
    order TRAMADOL online no membership overnight shipping
    cheap TRAMADOL in moreno valley
    order TRAMADOL no prescription cod payment
    buy cheap TRAMADOL in state of nebraska
    cheap TRAMADOL in pa
    buying cheapest TRAMADOL in state of louisiana
    order TRAMADOL in hi
    cheapest TRAMADOL in sweden
    buy cheapest TRAMADOL in state of alabama
    get TRAMADOL in istanbul
    order TRAMADOL in cambridge
    buy TRAMADOL money buy
    TRAMADOL buy in uk no prescription
    cheapest TRAMADOL uk cheap
    buy cheapest TRAMADOL in los angeles
    get TRAMADOL over the counter fedex
    order TRAMADOL on line without a prescription
    purchase TRAMADOL in greensboro
    purchase TRAMADOL in daly city
    order TRAMADOL on line without a rx
    TRAMADOL overnight delivery
    order TRAMADOL over the counter for sale
    TRAMADOL no prescription no membership
    buying cheap TRAMADOL in wv
    purchase cheap TRAMADOL in fl
    purchase cheap TRAMADOL in providence
    TRAMADOL buy in fra buy without prescription
    pharmacy tech buy TRAMADOL

  2. I really enjoy reading your blog, because you have a very clear opinion of things and stand up to it, which I respect a lot. However, I am often astonished.

Leave a Reply

Your email address will not be published. Required fields are marked *