Create a built in contact page for WordPress

Posted on 21st September, 2013 16 Comments

I do this for every theme I create and figured most of you would use a plugin, which is not really necessary. WordPress has mail functionality already so all we’re going to need to do is leverage that and add some style in the CSS.

  • Uses the administrators email address
  • Adds your site title to the subject line
  • includes a forward to sender option
  • Uses their email as the reply-to email
  • Includes a simple validation
  • Displays confirmation and error messages

Let’s start by creating a new document.

save this as contact-page.php.

To make this a template we’ll need to give it a name, simply add this to our new contact-page.php and it will instantly become a template.

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

Now add the PHP mailer.

The code has comments so should be easy to read.

<?php

  //response generation function

  $response = "";

  //function to generate response
  function generate_response($type, $message){

    global $response;

    if($type == "success") $response = "<div class='success'>{$message}</div>";
    else $response = "<div class='error'>{$message}</div>";

  }

  //response messages
  $not_human       = "Human verification incorrect.";
  $missing_content = "Please supply all information.";
  $email_invalid   = "Email Address Invalid.";
  $message_unsent  = "Message was not sent. Try Again.";
  $message_sent    = "Thanks! Your message has been sent.";

  //user posted variables
  $name = $_POST['message_name'];
  $email = $_POST['message_email'];
  $message = $_POST['message_text'];
  $human = $_POST['message_human'];

  //php mailer variables
  $to = get_option('admin_email');// include the admin email
  $subject = "Someone sent a message from ".get_bloginfo('name');
  $headers = 'From: '. $email . "rn" .
    'Reply-To: ' . $email . "rn";

  if(!$human == 0){
    if($human != 2) generate_response("error", $not_human); //not human!
    else {

      //validate email
      if(!filter_var($email, FILTER_VALIDATE_EMAIL))
        generate_response("error", $email_invalid);
      else //email is valid
      {
        //validate presence of name and message
        if(empty($name) || empty($message)){
          generate_response("error", $missing_content);
        }
        else //ready to go!
        {
          $sent = mail($to, $subject, $message, $headers);
          if($sent) generate_response("success", $message_sent); //message sent!
          else generate_response("error", $message_unsent); //message wasn't sent
        }
      }
    }
  }
  else if ($_POST['submitted']) generate_response("error", $missing_content);

?>

That takes care of the back-end, now for the actual page…

Directly below the mailer function above, add this code.

*I would check your theme’s page.php to see the code your theme uses for pulling in your pages content.

<?php
/*
 * -  Start the actual page
 */
get_header(); ?>

  <div id="primary" class="site-content">
    <div id="content" role="main">

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

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

            <header class="entry-header">
              <h1 class="entry-title"> <?php the_title(); ?> </h1>
            </header>

            <div class="entry-content">
              <?php the_content(); ?>

<!-- Now for the actual form -->

              <div class="contact-form">
                <?php echo $response; ?>
                <form action="#contact-form" method="post">
                  <div class="left">
                  <p><label for="name">Name: <span>*</span> <br><input type="text" name="message_name" value="<?php echo $_POST['message_name']; ?>"></label></p>
                  <p><label for="message_email">Email: <span>*</span> <br><input type="text" name="message_email" value="<?php echo $_POST['message_email']; ?>"></label></p>
                  </div>
                  <div class="right">
                  <p><label for="message_text">Message: <span>*</span> <br><textarea type="text" name="message_text"><?php echo $_POST['message_text']; ?></textarea></label></p>
                  </div>
                  <p><input type="checkbox" name="sendCopy" id="sendCopy" value="true"<?php if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true) echo ' checked="checked"'; ?> /><label for="sendCopy">Send a copy of this email to yourself</label></p>
                  <p><label for="message_human">Human Verification: <span>*</span> <br><input type="text" style="width: 60px;" name="message_human"> + 3 = 5</label></p>
                  <input type="hidden" name="submitted" value="1">
                  <p><input type="submit"></p>
                </form>
              </div>
 
<!-- End of the form -->

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

          </article><!-- #post -->

      <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->
  </div><!-- #primary -->

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

Finally add the CSS

Open your styles.css and add this.

 

/* WPT Contact Form
 * Error and confirmation messages
 * Form Styles
---------------------------------------------------------*/
  .error{
  padding: 5px 9px;
  border: 1px solid red;
  color: red;
  border-radius: 3px;
}

.success{
  padding: 5px 9px;
  border: 1px solid green;
  color: green;
  border-radius: 3px;
}
form[method=post] {
	padding-top: 50px;
}
form span{
  color: red;
}
.left {
	float: left;
	width: 35%;
}
.right {
	float: right;
	width: 65%;
}
.left input {
	width: 80% !important;
}
.right textarea {
	min-height: 200px;
	resize: vertical;
}

To select the contact page template simply select “add new page” from the left menu, then under the page attributes on the right select the “contact page template” and save the page. If you included the form below the_content() then you’ll be able to add anything above the contact form through the visual editor.

Comments

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]

pieter

22nd, Jan, 14

Thanks for the code. Only one concern, your code generate a few bugs in debug mode

WPtricks

08th, Feb, 14

That’s weird, What bugs are you receiving?

Austin Volz

18th, Aug, 20

Hello,
Do you want to change the way you deal with your anger and stress in times like these? Then join our online anger management class using ZOOM. Please remember anger does not disappear if anything it simply gets worse over time. Visit https://bit.ly/angermanage-uk for dates, time and costs.

Regards,

Mike Fisher (Anger Guru)

Noelia Napoli

19th, Aug, 20

Good evening, I was just visiting your site and submitted this message via your “contact us” form. The feedback page on your site sends you messages like this to your email account which is the reason you are reading through my message right now correct? That’s the holy grail with any type of online ad, getting people to actually READ your ad and I did that just now with you! If you have an advertisement you would like to promote to tons of websites via their contact forms in the US or to any country worldwide send me a quick note now, I can even focus on particular niches and my pricing is very affordable. Send a reply to: denzeljax219@gmail.com

Olivia Guy

28th, Aug, 20

Would you like to submit your advertisement on 1000’s of Advertising sites every month? One tiny investment every month will get you almost unlimited traffic to your site forever!

To get more info take a look at: https://bit.ly/free-traffic-always

Patrice Lovekin

01st, Sep, 20

Do you want more people to visit your website? Get hundreds of people who are ready to buy sent directly to your website. Boost revenues super fast. Start seeing results in as little as 48 hours. For more info Check out: https://bit.ly/more-traffic-4-your-site

Jodi

01st, Sep, 20

Hello there

Wear with intent, live with purpose. Fairly priced sunglasses with high quality UV400 lenses protection only $19.99 for the next 24 Hours ONLY.

Order here: kickshades.online

Best regards,

WPtricks | WordPress Theme Development

Aaron

04th, Sep, 20

Hi there,

Wouldn’t it be nice to add some fresh content to your site with zero added effort?

Stop working harder and Start working smarter.

It is a known fact that comments are counted as part of your content.

So sit back & relax while our commenters extend the life and value of your content with relevant comments.

For more details, hop over to: https://bulkcomments.net now or search in Google for BulkComments Blog Comment Service.

Use the coupon code: 100FREE-904-NFWF64EC to receive 100 FREE COMMENTS with any Bulk Comments pack (expires in 24 hours).

Best Regards,
Aaron
bulkcomments.net

RamonwaL

14th, Sep, 20

Good Morning

Work out to a whole new level with our P-Knee™ power leg knee joint support! 60% OFF and FREE Worldwide Shipping

Order here: p-knee.online

FREE Worldwide Shipping – TODAY ONLY!

Thank You,

Create a built in contact page for WordPress | WPtricks

Ruth Lipscomb

17th, Sep, 20

Hello, I was just on your website and filled out your “contact us” form. The contact page on your site sends you messages like this via email which is the reason you are reading through my message at this moment right? That’s the holy grail with any type of online ad, making people actually READ your ad and this is exactly what you’re doing now! If you have an ad message you would like to promote to tons of websites via their contact forms in the U.S. or anywhere in the world let me know, I can even target your required niches and my charges are very low. Send a reply to: LinaMaurusQE43@gmail.com

Lara Suter

22nd, Sep, 20

I WILL FIND POTENTIAL CUSTOMERS FOR YOU

I’m talking about a better promotion method than all that exists on the market right now, even better than email marketing.
Just like you received this message from me, this is exactly how you can promote your business or product.
SEE MORE => https://bit.ly/3lr6nLV

Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]