Development

How to Create a WordPress Contact Form Without a Plugin

banner-772x250

There are a lot of different plugins available to put a contact form on your WordPress site, but I like to use as few plugins as i can get away with. So if you feel the same way, here’s a simple way to add a contact form, with some simple cut & paste of your site’s existing page.php file.

First step – Create your page template

Copy the code from your page.php file into a new file and name it page-contact.php.

In order to let WordPress know this file should be treated as a page template, we need to add a comment at the beginning of this new file:

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

 

The page-contact.php file should now look something like this:

[php]<?php

/*

Template Name: Contact

*/

?>

 

<?php get_header() ?>

 

        <div id="container">

               <div id="content">

                       <?php the_post() ?>

                       <div id="post-<?php the_ID() ?>">

                               <div>

                               </div><!– .entry-content ->

                       </div><!– .post–>

               </div><!– #content –>

        </div><!– #container –>

 

<?php get_sidebar() ?>

<?php get_footer() ?>[/php]

 

Build the Form

Now you’ll need to create a simple contact form. This is very basic, allowing only name, email and comment fields.  It should be pasted into your page-contact.php file, within the entry-content div.

[php]</pre>
<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>
<pre>[/php]

 

Processing and Error Handling

Your form is taking shape now, but you still need it to verify submission and that required fields have been filled. When that is verified, it will get the admin’s email address and send the form to that address. if there’s a required field left blank, an error will be displayed.

Paste this code just before the get_header() function:

[php]<?php

if(isset($_POST[‘submitted’])) {

if(trim($_POST[‘contactName’]) === ”) {

$nameError = ‘Please enter your name.';

$hasError = true;

} else {

$name = trim($_POST[‘contactName’]);

}

&nbsp;

if(trim($_POST[’email’]) === ”)  {

$emailError = ‘Please enter your email address.';

$hasError = true;

} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST[’email’]))) {

$emailError = ‘You entered an invalid email address.';

$hasError = true;

} else {

$email = trim($_POST[’email’]);

}

&nbsp;

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’]);

}

}

&nbsp;

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;

&nbsp;

wp_mail($emailTo, $subject, $body, $headers);

$emailSent = true;

}

&nbsp;

} ?>[/php]

 

Now, you’ll get an error message beneath the applicable field of the form if an email address is incorrect  or a required field is left blank (such as  “Invalid email address”, or “Please enter your name”). Your entire page-contact.php file should now look like this:

[php]

<?php

/*

Template Name: Contact

*/

?>

&nbsp;

<?php

if(isset($_POST[‘submitted’])) {

if(trim($_POST[‘contactName’]) === ”) {

$nameError = ‘Please enter your name.';

$hasError = true;

} else {

$name = trim($_POST[‘contactName’]);

}

&nbsp;

if(trim($_POST[’email’]) === ”)  {

$emailError = ‘Please enter your email address.';

$hasError = true;

} else if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", trim($_POST[’email’]))) {

$emailError = ‘You entered an invalid email address.';

$hasError = true;

} else {

$email = trim($_POST[’email’]);

}

&nbsp;

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’]);

}

}

&nbsp;

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;

&nbsp;

wp_mail($emailTo, $subject, $body, $headers);

$emailSent = true;

}

&nbsp;

} ?>

<?php get_header(); ?>

<div id="container">

<div id="content">

&nbsp;

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div <?php post_class() ?> id="post-<?php the_ID(); ?>">

<h1><?php the_title(); ?></h1>

<div>

<?php if(isset($emailSent) && $emailSent == true) { ?>

<div>

<p>Thanks, your email was sent successfully.</p>

</div>

<?php } else { ?>

<?php the_content(); ?>

<?php if(isset($hasError) || isset($captchaError)) { ?>

<p>Sorry, an error occured.<p>

<?php } ?>

&nbsp;

<form action="<?php the_permalink(); ?>" id="contactForm" method="post">

<ul>

<li>

<label for="contactName">Name:</label>

<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST[‘contactName’])) echo $_POST[‘contactName’];?>" />

<?php if($nameError != ”) { ?>

<span><?=$nameError;?></span>

<?php } ?>

</li>

&nbsp;

<li>

<label for="email">Email</label>

<input type="text" name="email" id="email" value="<?php if(isset($_POST[’email’]))  echo $_POST[’email’];?>" />

<?php if($emailError != ”) { ?>

<span><?=$emailError;?></span>

<?php } ?>

</li>

&nbsp;

<li><label for="commentsText">Message:</label>

<textarea name="comments" id="commentsText" rows="20" cols="30"><?php if(isset($_POST[‘comments’])) { if(function_exists(‘stripslashes’)) { echo stripslashes($_POST[‘comments’]); } else { echo $_POST[‘comments’]; } } ?></textarea>

<?php if($commentError != ”) { ?>

<span><?=$commentError;?></span>

<?php } ?>

</li>

&nbsp;

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

&nbsp;

<?php endwhile; endif; ?>

</div><!– #content –>

</div><!– #container –>

&nbsp;

<?php get_sidebar(); ?>

<?php get_footer(); ?>
<pre>
[/php]

If you have the coding skills, you can customize that contact form as you see fit, adding fields or exporting to a database. But this is a good start, and you’ll have eliminated one more plugin.

Wissam Dandan
Merging English & Arabic search into a global business market. Strong understanding of SEO, Web Analytics & SM strategy. International SEO Consultant.
36 Comments
  • Linda Apr 11,2015 at 2:31 am

    Wow! Thanks! The contact form looks definitely great :) I truly appreciated it.

  • joe Apr 4,2015 at 11:19 pm

    thank you for useful article

  • neny Aug 2,2014 at 7:48 am

    validation is not working

  • Grietje Goedkoop Jun 29,2014 at 7:58 pm

    Thanks for this great post.
    Would this work in a sidebar widget?
    Been trying all sorts of different varieties but no luck so far.
    Thanks.

  • lirikpedia Jun 12,2014 at 12:52 pm

    Great!. How to prevent spamming? is there any solution to add recaptcha?

  • dlm Jun 5,2014 at 3:24 pm

    Hello and thank you for this form.
    I was wondering how can i go about changing the email to instead than to the admin the message can be sent to someone else, or to more than one party?
    Thank you for your time.
    D

  • josué Corrêa Lima May 30,2014 at 10:16 pm

    Very good tutoral plus how do I configure to be sent to a different email?

  • Francisco Mar 26,2014 at 4:50 pm

    Hi! thank you for this great contact form!!

    Urgent help!

    I need to show the label inside the entrance and make disappear “onfocus” … here’s part of my code wiht your code:

    value=”Teléfono ” onfocus=”if(this.value==’Teléfono’)this.value=””

    but when I click on the field label does not disappear …

  • jacob Mar 5,2014 at 10:29 am

    i can’t see who is contact me..how i can see this plz ,info me…

  • e Park Ltd Jan 24,2014 at 3:35 am

    Thank you for sharing

  • […] منبع: wissamdandan.com […]

  • Danielle Sastrawan Nov 15,2013 at 11:48 am

    I need to create a registration form… just something that will send me an email if they want to sign up to a particular retreat. Problem is, I am working on an online server and don’t have WordPress installed in my computer, so I do not have access to the main admin panel. I can’t create any theme pages or download plugins, etc. My background is in design, not web programming. We got someone else to build my design and I have access to update, create new pages, etc. I’ve managed to figure out how to do all sorts of stuff (like rollovers – probably not a big deal to you guys, I’m sure, but that was an epiphany for me) and I’m thinking there has GOT to be a way that I can just put some code in the page source that will get a form going. All I need is the name, email, re: (which retreat they want) and message box and for it to be sent to my email address. Just want to know if that’s possible given my limitations or do I have to call my web guy to do it?

    Any help would be appreciated. Thanks, Danielle.

  • Shihab Oct 26,2013 at 4:48 am

    This tree errors…. :(
    Notice: Undefined variable: nameError in C:\xampp\htdocs\theme\wp-content\themes\xotil\hz-contact.php on line 141
    Email
    Notice: Undefined variable: emailError in C:\xampp\htdocs\theme\wp-content\themes\xotil\hz-contact.php on line 149
    Message:
    Notice: Undefined variable: commentError in C:\xampp\htdocs\theme\wp-content\themes\xotil\hz-contact.php on line 156

  • vijay Oct 15,2013 at 4:53 pm

    Really want to thank you for your help. You saved me from putting a new trouble on my site in the form of a plugin :)

  • Mukesh Jangir Oct 4,2013 at 10:18 am

    Great Job :)

  • Jo Sep 26,2013 at 10:06 pm

    This didnt work for me unfortunately. All the codes entered showed up on front end of site

    • Wissam Dandan Oct 17,2013 at 2:04 pm

      re do the page ..you might forgot a “<” or something

  • I Wayan Widyana Sep 21,2013 at 1:36 pm

    Hi, thanks. Work perfectly. 😀

  • Gunaseelan Sep 20,2013 at 10:05 am

    $emailTo = get_option(‘tz_email’); ==> Please Explain this code.

    • Elephont Feb 18,2014 at 5:46 pm

      This is supposed to get the email address from a settings field named ‘tz_email’ in your theme options page (WordPress Settings API), if you have one of course 😉

  • Gunaseelan Sep 20,2013 at 8:32 am

    Hi Wissam Dandan,

    It is superb.

    I need to control contact form fields from WP Admin Panel. Please guide me how to do?

    It would be fine if it is quick.

    Thanks in advance.

    • Wissam Dandan Sep 22,2013 at 11:59 am

      its not that easy .. for your requirements its better to have a plugin like CF7

  • lakshman Sep 6,2013 at 10:05 am

    What is page.php and where it is available.. please tell me

  • MatthewR Aug 27,2013 at 7:29 pm

    I want to place this on the bottom of a page with other posts. Are there simple changes I can make to do so?

    • Wissam Dandan Aug 27,2013 at 7:45 pm

      there is a solution but you need to edit the file that it aggregates all your posts and add the code of mine to the file.
      if it didnt work the best solution is use a plugin for the implementation

  • phild Jul 17,2013 at 4:49 am

    works great so long as its contained in a single page/post. If contained on a page with other posts, this will “loop” for each post displaying multiple forms. Ex. as a sidebar. Any way to create an email form post on page with other posts?

  • nilesh Jul 2,2013 at 2:50 pm

    i am getting an

    Notice: Undefined offset: 1 in D:\wamp\www\wordpressproject\offlineTheme\wp-includes\query.php on line 2831

    when Wp Debug in true .

    please tell me the solution…

    well thanks for posting i have already implimented

    • Wissam Dandan Jul 11,2013 at 5:11 pm

      try to :
      -deactivating all plugins to see if this resolves the problem. If this works, re-activate the plugins one by one until you find the problematic plugin(s).

      – switching to the default theme to rule out any theme-specific problems.

  • Fansi Jun 28,2013 at 12:38 am

    Thank you for sharing! Anyway, how to put the form inside a page template i.e. footer.php?

    • Wissam Dandan Jul 2,2013 at 1:25 pm

      choose from the template on the right side when you create a page

  • yogesh Jun 12,2013 at 7:34 am

    this is very good code but let me know how to use?
    i have create file as well as your code but i dont understand.
    so please tell me sir.

    thanks
    yogesh

    • Wissam Dandan Jun 12,2013 at 3:56 pm

      you have to add a page and choose from templates the “contact” page template and save and publish :) Cheers

  • Damith Jun 4,2013 at 11:29 am

    Wissam,

    How to publish this page and view it.

    Damith

    • admin Jun 4,2013 at 11:53 pm

      When you add a new page from the template (on the right side) choose page contact and publish

  • John May 28,2013 at 6:38 pm

    I used following article for creating the contact form and it is working nice for me.
    http://wordpressapi.com/2010/11/26/create-contact-page-wihout-wordpress-plugin/

    It is very simple to use the any wordpress site.

  • Danny May 9,2013 at 10:18 pm

    Wissam,
    This is a value bomb! Thank you for sharing. Just implemented on one of my sites.
    Danny

Leave Your Comment

Your Name*
Your Webpage

Your Comment*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

css.phpReal Time Web Analytics