Create a built in contact page for WordPress

Posted on 21st September, 2013 306 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

Santo

02nd, Oct, 20

Morning

Defrost frozen foods in minutes safely and naturally with our THAW KING™.

50% OFF for the next 24 Hours ONLY + FREE Worldwide Shipping for a LIMITED time

Buy now: thawking.online

Best Wishes,

Create a built in contact page for WordPress | WPtricks

Marlon Breaux

14th, Oct, 20

Looking for fresh buyers? Receive tons of people who are ready to buy sent directly to your website. Boost revenues fast. Start seeing results in as little as 48 hours. For more info Have a look at: http://bit.ly/buy-website-visitors

JamesVen

21st, Oct, 20

end of one’s tether with the Technician Ave labelШ°ВІs protests [url=https://ciamedusa.com/#]how to order cialis online[/url] narrow impersonation may second-rate cialis generic online an aberrant j.

Maximo Brucken

24th, Oct, 20

I have been examinating out some of your articles and it’s clever stuff. I will make sure to bookmark your website.

Juliane Scollen

26th, Oct, 20

Greetings, I was just taking a look at your website and filled out your “contact us” form. The feedback page on your site sends you messages like this to your email account which is the reason you’re reading my message at this moment correct? That’s the most important accomplishment with any kind of advertising, getting people to actually READ your ad and that’s exactly what I just accomplished with you! If you have something you would like to blast out to thousands of websites via their contact forms in the US or to any country worldwide let me know, I can even focus on particular niches and my prices are super low. Write an email to: erwanleroux9138@gmail.com

Charleswam

05th, Nov, 20

Любµшь фýтбòл, á жèнa ругáèтся?
Ηе хочешь экономить, хочешь разбогатеть? До 500$ в день — µ ты богат! Ρазбогатеть
https://goo-gl.ru.com/3EQ

Charleswam

09th, Nov, 20

Êщe одµн способ зápáботкa для дòмохòзяèк!
Боùшься смотреть на ценнùки? Γлотаешь успокоительное пачкамù? Бессоннùца достала? 100 000 рублей ежемесячно: пусть κрùзµс, глядя на тебя, пьет успоκоùтельное! Подробностù тут
https://goo-gl.ru.com/3EQ

Martha Lawless

11th, Nov, 20

No more paying way too much money for expensive Facebook advertising! We’ve got a system that requires only a small bit of cash and results in an almost indefinite amount of web visitors to your website

Check out our site now: http://bit.ly/no-cost-traffic-4-your-site

Cissr

12th, Nov, 20

Generic
cialis discount [url=https://cciialiss.com/]best generic cialis[/url] cialis used women

Cissr

12th, Nov, 20

Generic
cialis in london [url=https://cciialiss.com/]tadalafil cialis[/url] cialis soft pills

Cissr

13th, Nov, 20

Generic
many pills cialis [url=https://cciialiss.com/#]buy online[/url] cialis ireland

Cissr

13th, Nov, 20

Brand
cialis on line order [url=https://cciialiss.com/]buy cialis online[/url] buy generic cialis online without a prescription

Cciialiss

13th, Nov, 20

USA
cialis everyday cost [url=https://cciialiss.com/]buy cialis canada[/url] cialis levitra online

Cciialiss

13th, Nov, 20

Generic
cialis recipe [url=https://cciialiss.com/]5mg cialis[/url] cialis france online

Charleswam

13th, Nov, 20

100 тыcяч eжeмècячнò — µ к гaдaлкè нe хòди!Не знаешь, что ждет тебя через месяц? Заработок до 500$ в день — это реальность. Узнай подробности!
https://bit.ly/3pxwXFd

Cciialiss

13th, Nov, 20

USA
will insurance cover cialis [url=https://cciialiss.com/]generic cialis buy[/url] cialis tablets

Cciialiss

13th, Nov, 20

Brand
females using cialis [url=https://cciialiss.com/]cialis 20mg[/url] cialis used for

Cciialiss

14th, Nov, 20

USA
cialis from canada [url=https://cciialiss.com/]buy cialis usa[/url] cialis 5 mg dose

Cciialiss

14th, Nov, 20

Generic
generic levitra cialis [url=https://cciialiss.com/]buy cialis brand[/url] price cialis pharmacy

Cciialiss

14th, Nov, 20

Brand
cialis once days [url=https://cciialiss.com/]cialis 20mg pills[/url] buy generic cialis online uk

Cciialiss

14th, Nov, 20

Brand
buying brand name cialis [url=https://cciialiss.com/]generic cialis[/url] buy cialis paypal

Cciialiss

15th, Nov, 20

Generic
know if need cialis [url=https://cciialiss.com/]cialis 20mg[/url] cialis users review

Cciialiss

15th, Nov, 20

Generic
buy generic cialis canada [url=https://cciialiss.com/]cialis pills[/url] cialis online uk

Cciialiss

15th, Nov, 20

Brand
cheap legal cialis [url=https://cciialiss.com/]buy cialis canada[/url] milligrams of cialis

Cciialiss

15th, Nov, 20

USA
cialis one day online [url=https://cciialiss.com/]cialis generic online pharmacy[/url] cialis better food

Cciialiss

15th, Nov, 20

USA
exercise on cialis [url=https://cciialiss.com/]cialis 20mg[/url] buy generic cialis pills

Cciialiss

15th, Nov, 20

Brand
cialis de 50mg [url=https://cciialiss.com/]buy cialis brand[/url] brand cialis online pharmacy

Cciialiss

16th, Nov, 20

USA
cialis pharmacy rx one [url=https://cciialiss.com/]cialis without prescriptions[/url] everyday cialis use

Cciialiss

16th, Nov, 20

Generic
cialis insurance coverage [url=https://cciialiss.com/]buy cialis usa[/url] cialis fast delivery uk

Cciialiss

16th, Nov, 20

Brand
buying cialis europe [url=https://cciialiss.com/]cialis generic online pharmacy[/url] daily cialis new zealand

Steve Wilson

16th, Nov, 20

Hi, We are wondering if you would be interested in our service, where we can provide you with a dofollow link from Amazon (DA 96) back to wptricks.co.uk?

The price is just $77 per link.

To explain what DA is and the benefit for your website, along with a sample of an existing link, please read here: https://pastelink.net/1nm60

If you’d be interested in learning more, reply to this email but please make sure you include the word INTERESTED in the subject line field, so we can get to your reply sooner.

Kind Regards,
Steve

ccialisny

17th, Nov, 20

buy cialis legally [url=https://ccialisny.com/]ordering cialis online australia[/url] cialis everyday cost

Charleswam

17th, Nov, 20

Нe хвaтáeт нa òтпýcк? Зaрaботaй нá Туpцµю зa мècяц!
Ежедневные траты не дают возможности наκопùть деньгµ? Хватùт считать κаждую копейκу! Ты можешь зарабатывать, не выходя µз дома! Подробности тут
https://bit.ly/2IJLNHK

ccialisny

17th, Nov, 20

lowest dose of cialis [url=https://ccialisny.com/]order cialis 20mg[/url] best price of cialis

ccialisny

18th, Nov, 20

online purchase of cialis [url=https://ccialisny.com/]overnight cialis order[/url] cialis side effects in men

ccialisny

18th, Nov, 20

cialis hydroxycut [url=https://ccialisny.com/]order cialis brand[/url] tadalafil buy

llevitraaa

19th, Nov, 20

perbedaan viagra cialis levitra [url=https://llevitraa.com/]generic levitra buy online australia[/url] precio levitra bucodispersable 10 mg

llevitraaa

19th, Nov, 20

levitra instrucciones [url=https://llevitraa.com/]levitra buy in uk online[/url] levitra 20mg vs viagra 50 mg

llevitraaa

20th, Nov, 20

vademecum levitra 10 mg [url=https://llevitraa.com/]generic levitra buy online[/url] levitra panvel

llevitraaa

20th, Nov, 20

io uso levitra [url=https://llevitraa.com/]generic levitra buy[/url] se puede tomar levitra con enalapril

llevitraaa

20th, Nov, 20

levitra kaufen erfahrungen [url=https://llevitraa.com/]levitra wholesale no prescription[/url] levitra legal bestellen

llevitraaa

20th, Nov, 20

comparatif levitra viagra cialis [url=https://llevitraa.com/]llevitraa.com[/url] best levitra dose

llevitraaa

21st, Nov, 20

levitra 10 mg schmelztabletten ohne rezept [url=https://llevitraa.com/]costco pharmacy prices levitra[/url] does levitra lower your blood pressure

llevitraaa

21st, Nov, 20

levitra dosage 10 mg [url=https://llevitraa.com/]generic levitra[/url] differences between viagra cialis and levitra video

Johan Fourie

24th, Nov, 20

Hey.

After reading through wptricks.co.uk I think we might be able to assist each other.

I would love to speak to you about it and get you on the fast track to easy bulk mailing.

Let me know if we can setup a call sometime or visit our landing page http://www.EmailCave.com

Regards,
Johan
Skype: cmsdevelopers

fixcialel

24th, Nov, 20

cialis efectos colaterales [url=https://cialisfix.com/]order cheap cialis online[/url] cialis before

fixcialel

24th, Nov, 20

buy real cialis cheap [url=https://cialisfix.com/]order cheap cialis online[/url] cialis internet pharmacy

Charleswam

25th, Nov, 20

Врèмя — дeньги! Потòрòпµcь зápáбòтaть cвоµ!
Ηадоело работать на чужого дядю? Зарабатывай до 500$ в день! Πосмотреть, κак это работает
https://plbtc.page.link/j5nk

fixcialel

25th, Nov, 20

buy cialis england [url=https://cialisfix.com/]order cialis 20 online[/url] cialis initial dose

fixcialel

25th, Nov, 20

cialis bestellen [url=https://cialisfix.com/]overnight cialis order[/url] cialis prevent headache

ciialel

28th, Nov, 20

purchase cialis [url=https://cciialiis.com/]ordering cialis in canada[/url] buy cialis without prescription

ciialel

28th, Nov, 20

brand cialis for sale [url=https://cciialiis.com/]cialis order online[/url] using cialis women

Charleswam

29th, Nov, 20

100 тыcяч eжèмecячно — и к гaдáлкe нè хòдµ!
Даже в κризис можно жùть шиκарно! Мы предлагаем тебе заработать реальные деньгµ! Τы получùшь их всего за месяц! Ηе верµшь? Πроверь
https://is.gd/HWDxGZ

ciialel

29th, Nov, 20

cialis 30 day cost [url=https://cciialiis.com/]cialis ordering australia[/url] mix cialis with levitra

ciialel

29th, Nov, 20

effect cialis normal men [url=https://cciialiis.com/]mail order and cialis[/url] cialis effect kidneys

Cciialiss

29th, Nov, 20

Generic
cheap cialis in usa [url=https://cciialiss.com/]order cialis brand[/url] whats cialis do

Cciialiss

30th, Nov, 20

USA
cialis mg dose [url=https://cciialiss.com/]cialis order online[/url] cheaper levitra cialis

Cciialiss

30th, Nov, 20

Brand
wellbutrin with cialis [url=https://cciialiss.com/]order cialis canada[/url] class of cialis

Cciialiss

30th, Nov, 20

Brand
is cialis for women [url=https://cciialiss.com/]order cialis miami[/url] clinical name cialis

Cciialiss

01st, Dec, 20

Brand
cialis product review [url=https://cciialiss.com/]order cialis online[/url] tadalafil discount

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]