Codeable info

Setting Up A Native Contact Page Without Using A WordPress Plugin

Posted on by in WordPress Tutorials

WordPress natively supports the setup of a personal or business contact form to allow site visitors to contact you directly. However the default WordPress theme doesn’t include a pre-installed contact form page.

In most cases WordPress users would turn to an external plugin to add the related Contact form, without realizing that it could cause its own series of problems. Plugins always serve as a weakness for hacking and hijacking opportunities, especially if they are out of date. Also, a blog can load slower and take more time to display on screen if too many plugins are running.

Therefore the best option is almost always to directly integrate a feature without the use of a plugin. That being said in this tutorial you will learn how to setup an integrated contact form within your WordPress install.

Contact Form Page Template

WordPress comes with the integrated use of custom templates for various pages which ultimately allows users the option to give each page unique appearances.

Creating a page template for the contact form is where we will start, as it provides the base appearance and function of the page.

To begin, copy the “Page.php” source file (for the active theme of the related WordPress blog or site) and rename the copy to “Contact.php”.

After that has been completed we need to add information into the beginning of the new “Contact.php” file to inform WordPress that it is a template. Input the following code at the very beginning of the file:

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

The “Contact.php” file should now resemble the following:

<?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() ?>

The section between the “<div id=”container”>” opening and closing tags needs to be added into your new “Contact.php” between the “get_header()” and “get_footer()” tags. Some themes may already have this information, or something similar, implemented- just make sure it is all there.

Adding In The Contact Form Code

Next we must add in the code to display the contact form and related information. In order to do this we are going to add to the pre-existing code. The following code needs to go between the “entry-content” opening and closing tags:

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

Contact Form Functions

The next bit of code will tell WordPress how to handle the contact form and will search for the admin’s email address and then send the related email where it belongs. Make sure to input the following code segment after the page template heading we added in the first step 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 nnEmail: $email nnComments: $comments";
		$headers = 'From: '.$name.' <'.$emailTo.'>' . "rn" . 'Reply-To: ' . $email;
		mail($emailTo, $subject, $body, $headers);
		$emailSent = true;
	}
} ?>

What The Final Product Should Resemble

All in all if done correctly the entire “Contact.php” page we have created should look like the following bit of code (if you want to cheat you can simply copy this entire length of code instead of following the steps above):

 
<?php
/*
Template Name: Contact Form
*/
?>
 
$_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 nnEmail: $email nnComments: $comments";
		$headers = 'From: '.$name.' <'.$emailTo.'>' . "rn" . '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></textarea>
									<span class="error"></span>
							</li>
							<li>
								Send email
							</li>
						</ul>
					</form>
				</div><!-- .entry-content -->
			</div><!-- .post -->
		</div><!-- #content -->
	</div><!-- #container -->

Setting Up The Contact Page

To continue you simply need to design the contact page however you would like by either using the native WordPress page editor or an external html editing program. After loading the new file into your WordPress database you should be able to access it using the native WordPress visual editor.

In order to use the new Contact template we just set up we need to select it for use by the new contact page. In the admin panel/ WordPress dashboard simply navigate to “Appearance > Editor” and the page template in question (Contact.php) should now be included in the list. Take note that this is a page template and not the actual page.

Page Attributes MenuIn order to create the contact page you will need to set up a new page under the “Pages” tab (if you haven’t already designed a new page as mentioned in the beginning of this section). After the new page has been added you should be able to select the “Contact.php” template in the right hand side (the “Template” drop down menu under “Page Attributes”).

Note: Some options may be removed from sight to clean up the control panel, if you do not see a “Page Attributes” section simply click the “screen options” button in the top right of the page and ensure the check box next to “Page Attributes” is marked.

Wallah, you should now have a fully functioning contact page for use on your WordPress enabled blog or website.

)
Codeable info

Comments (8)

Comment by Jon says:

Very cool. Quick question, will this form work automatically with Akismet? Thanks.

Comment by Farlando says:

Nice tutorial, I do have one question. can the data be saved in a database instead of sending it to an email address.

I want to implement something that I could customize my form, then save the data in a database instead of emailing the same. I tried using $wpdb but I couldn’t get it to work.

Comment by Akesh says:

please help me,I want 2 fields required to send in mail using wordpress(dont use plugins),so please help me

Comment by Dustin says:

Thanks! Giving this a shot right now.

Comment by valdejaim says:

Hello Briley

Thank you by your usefull post. I’ve modified the code to adapt to my own site but the guide has opened my eyes.

Kind Regards from Venezuela

Comment by Vivek Parmar says:

That’s a great work only i have installed the plugin and using the default one like shown in first screen-shot. thanks for the tut now i will add more funtionality in it

Comment by Briley Kenney says:

Hey Alan, steps to make sure.

1. Make sure you implemented the very first template information in your “Contact.php” file. Also when creating a new page (last step in tutorial) make sure to select the new Contact Form page as the template.

2. Your “Contact.php” page will always look slightly different depending on the active theme you have running in your WordPress install. Make sure the second code (“What your Contact.php file should resemble”) is included in your file. More specifically the “div id container section”.

3. The next bit of code goes between the “entry-content” opening and closing tag; I apologize I should have been more clear about this in my tutorial.

4.The contact form functions code goes between the first template information we entered and the “get_header()” function.

If you implemented the above code and copied it correctly there should be no parse error. My guess is that you input the above code in the wrong place or forgot to implement part of it.

Let me know if this helps or if you have any other problems. :)

Comment by Alan says:

Hi Briley,

Thanks for putting together this tutorial. Am I skipping a step? I am getting this message when I nav to the contact page.
Parse error: syntax error, unexpected $end in /home/content/x/x/x/xxxxxx/html/xxxxxxx/wp-content/themes/modxblog/Contact.php on line 65

Codeable info