How to Create a WordPress Contact Form Without a Plugin

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.


Comments

34comments
  • author avatar
    Danny
    2 years ago Reply

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

  • author avatar
    John
    1 year ago Reply

    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.

  • author avatar
    Damith
    1 year ago Reply

    Wissam,

    How to publish this page and view it.

    Damith

    • author avatar
      admin
      1 year ago Reply

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

  • author avatar
    yogesh
    1 year ago Reply

    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

    • author avatar
      Wissam Dandan
      1 year ago Reply

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

  • author avatar
    Fansi
    1 year ago Reply

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

    • author avatar
      Wissam Dandan
      1 year ago Reply

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

  • author avatar
    nilesh
    1 year ago Reply

    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

    • author avatar
      Wissam Dandan
      1 year ago Reply

      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.

  • author avatar
    phild
    1 year ago Reply

    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?

  • author avatar
    MatthewR
    1 year ago Reply

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

    • author avatar
      Wissam Dandan
      1 year ago Reply

      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

  • author avatar
    lakshman
    1 year ago Reply

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

  • author avatar
    Gunaseelan
    1 year ago Reply

    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.

    • author avatar
      Wissam Dandan
      1 year ago Reply

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

  • author avatar
    Gunaseelan
    1 year ago Reply

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

    • author avatar
      Elephont
      9 months ago Reply

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

  • author avatar

    Hi, thanks. Work perfectly. :D

  • author avatar
    Jo
    1 year ago Reply

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

  • author avatar
    Mukesh Jangir
    1 year ago Reply

    Great Job :)

  • author avatar
    vijay
    1 year ago Reply

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

  • author avatar
    Shihab
    1 year ago Reply

    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

  • author avatar

    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.

  • author avatar
    e Park Ltd
    10 months ago Reply

    Thank you for sharing

  • author avatar
    jacob
    9 months ago Reply

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

  • author avatar
    Francisco
    8 months ago Reply

    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 …

  • author avatar
    josué Corrêa Lima
    6 months ago Reply

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

  • author avatar
    dlm
    6 months ago Reply

    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

  • author avatar
    lirikpedia
    5 months ago Reply

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

  • author avatar
    Grietje Goedkoop
    5 months ago Reply

    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.

  • author avatar
    neny
    4 months ago Reply

    validation is not working

Leave a Reply

css.phpReal Time Analytics