Create a contact form for WordPress without using a plugin

Why not just use a plugin?

WordPress plugins are one of the great strengths of the platform, but there are plenty of good reasons why sometimes you might not what to use them. Each plugin you add to your site will affect speed and security so it's always important to consider if you really need a plugin or if the functionality is something you can implement yourself.

In today's example of a contact form, there are some excellent form building plugins out there (check out Ninja Forms or Contact Form 7), which come with a huge range of functionality. But what if we just want to email a simple contact form? The aforementioned plugins will add a lot of additional CSS, javascript and make changes to your database. They will require updating and have added code you are relying on to be secure and that may affect the speed of your site (try typing 'contact form 7 slows site' into Google).

So, in today's tutorial we'll be looking at how you can create a simple, light-weight, email based contact form that you can create with a single page template.

The approach

In this tutorial we'll be going through the following steps to create a contact form:

  • Create a new page template
  • Create a new page and assign the template
  • Generate some HTML5 markup for the template
  • Generate some CSS styling
  • Generate some PHP to validate and email the form
  • Test the form and email

We'll be using the Coveloping HTML5 Responsive Form Generator to create some of the code, meaning it will automatically be using HTML5 fields, validation and be responsive to different screen sizes (all code examples are provided if you don't have membership access to the tool).

Step-by-step creating a simple contact form without a plugin

Before we get started, it's assumed that you're working locally on a WordPress site for the duration of this tutorial, if you're working on a server you would need to upload the template file / css to your server via FTP in between making changes in the admin area.

Create a new template

The first step is to create a new template file. This is very straight forward and once set up will mean when you create new pages in WordPress it will display as a template option on the right hand side. Inside /wp-content/themes/your-theme/page-templates add a PHP file with the following header:

<?php
/**
 * Template Name: Basic Contact Form
 */
?>
<?php get_header(); ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>
Next go to your WordPress admin area and create a new page for the contact form. You should now see you can select the template on the right hand side.

Save the page. If you try and browse to it now you should see your header, footer and sidebar, but an otherwise empty page - this is because it is only using the contents of the page template we created, which is currently empty. So lets start building up template.

dropdown

Create the form

Now we're going to create our form. You can write the code from scratch, or you can use our HTML5 Responsive Form Generator, which will generate all the code for you.

In this example we'll use one of the available templates 'Contact Form with Email Script'. You can customise this form using the interface, or use the code we've provided below to use as it's shown in the screenshot.

Screenshot from 2016-01-07 11:34:28

Form Markup - HTML5

The following HTML code is a responsive form, using HTML5 for validating the different field types. This code want's to sit between the get_header function and before the get_sidebar function in the template file (we'll show the whole file shortly).

<form id="form" class="form" name="form" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
    <h1>Get in touch</h1>
    <div class="form-content">
        <div class="intro"><p>Use the form below to get in touch!</p></div>
        <h2 class="section">Your Details</h2>
        <div id="section1">
            <div class="field"><div class="edit-options"><div class="edit"></div><div class="delete"></div></div><label for="FirstName">First Name</label><input type="text" id="FirstName" name="FirstName" required></div>
            <div class="field"><label for="SecondName">Second Name</label><input type="text" id="SecondName" name="SecondName" required></div>
            <div class="field"><label for="Email">Email</label><input type="email" id="Email" name="Email" required></div>
            <div class="field"><label for="Telephone">Telephone</label><input type="tel" id="Telephone" name="Telephone"></div>
        </div>
        <h2 class="section">Message</h2>
        <div id="section2">
            <div class="field"><label for="About">About</label><select id="About" name="About"><option value="general">General Enquiry</option><option value="service">Services</option><option value="product">Products</option></select></div>
            <div class="field"><textarea id="Message" name="Message" wrap="hard" required></textarea></div>
            <div class="field"><input type="submit" id="SubmitForm"></div>
        </div>
    </div>
</form>
<link href="http://fonts.googleapis.com/css?family=Roboto" id="google-font-selector" rel="stylesheet" type="text/css">

Form CSS

Now we add the styling for the form. Add this into your style.css file in the root of your theme directory.

.form{ 
    max-width: 90%; 
    min-width: 25%; 
    color: #3A5261; 
    font-size: 14px; 
    margin: auto; 
    background-color: #FFFFFF; 
    padding: 40px; 
} 
.form-content{ 
    margin: 0px; 
} 
.form label{ 
    color: #222222; 
    font-size: 14px; 
} 
.form div{ 
    auto: width; 
} 
.form input, form textarea, form select{ 
    border-width: 1px; 
    border-style: solid; 
    border-color: #6E9BB8; 
    border-radius: 0px; 
    padding: 3px; 
    width: 100%; 
} 
.form input[type=radio], input[type=checkbox]{ 
    margin: 10px; 
    width: 13px; 
} 
.form, .form h1, .form h2{ 
    font-family: 'Roboto', sans-serif;; 
} 
.form h1{ 
    font-size: 40px; 
    color: #3A5261; 
    padding: 0px; 
    margin: 0px; 
    margin-bottom: 10px; 
    border-bottom-style: dotted; 
    border-bottom-color: #CCCCCC; 
    border-bottom-width: 2px; 
    border-radius: 0px; 
    background-color: #FFFFFF; 
} 
.intro{ 
    margin-bottom: 10px; 
} 
.clear{ 
    clear: both; 
} 
.form textarea{ 
    height: 50px; 
    width: 100%; 
} 
.form input[type=submit]{ 
    width: 100%; 
    background-color: #3A5261; 
    color: #CFEAFF; 
} 
.field{ 
    margin-bottom: 15px; 
} 
.alert{ 
    color: _#468847; 
    padding: 15px; 
    border: 1px solid transparent; 
    border-radius: 4px; 
} 
.alert-success{ 
    color: #468847; 
    background-color: #dff0d8; 
    border-color: #d6e9c6; 
} 
.alert-danger{ 
    color: #a94442; 
    background-color: #f2dede; 
    border-color: #ebccd1; 
}

Form Validation and Email

Lastly the heavy lifting - the PHP part of the script will check if the form is being posted, then check all the required fields are complete. If they are, it will validate each of the fields using PHP's filter_var function, and then either display the errors, or post the form variables using PHP's send_mail function. This code belongs under the header, don't forget to change the email address!

<?php 
if ($_SERVER['REQUEST_METHOD'] === 'POST'){ 

    if (!isset($_POST['FirstName']) || !isset($_POST['SecondName']) || !isset($_POST['Email'])){ 

        $errors .= 'Please complete all the required fields.'; 
     } 

    if ($_POST['FirstName'] != "") { 
        $_POST['FirstName'] = filter_var($_POST['FirstName'], FILTER_SANITIZE_STRING); 
        if ($_POST['FirstName'] == "") { 
            $errors .= 'First Name is not valid.<br/>'; 
        }
    }
 
    if ($_POST['SecondName'] != "") { 
        $_POST['SecondName'] = filter_var($_POST['SecondName'], FILTER_SANITIZE_STRING); 
        if ($_POST['SecondName'] == "") { 
            $errors .= 'Second Name is not valid.<br/>'; 
        }
    }
 
    if ($_POST['Email'] != "") { 
        $email = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL); 
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
            $errors .= 'Email is not valid.<br/>'; 
        }
    }
 
    if ($_POST['Telephone'] != "") { 
        $_POST['Telephone'] = filter_var($_POST['Telephone'], FILTER_SANITIZE_STRING); 
        if ($_POST['Telephone'] == "") { 
            $errors .= 'Telephone is not valid.<br/>'; 
        }
    }
 
    if ($_POST['About'] != "") { 
        $_POST['About'] = filter_var($_POST['About'], FILTER_SANITIZE_STRING); 
        if ($_POST['About'] == "") { 
            $errors .= 'About is not valid.<br/>'; 
        }
    }
 
    if ($_POST['Message'] != "") { 
        $_POST['Message'] = filter_var($_POST['Message'], FILTER_SANITIZE_STRING); 
        if ($_POST['Message'] == "") { 
            $errors .= 'Message is not valid.<br/>'; 
        }
    }
 
    if(!isset($errors)) { 
        $to = 'you@yoursite.com'; 
        $from = $_POST['Email']; 
        $subject = 'Contact Form Submission'; 
        $content = "
        First Name: " . $_POST['FirstName'] . "
        Second Name: " . $_POST['SecondName'] . "
        Email: " . $_POST['Email'] . "
        Telephone: " . $_POST['Telephone'] . "
        About: " . $_POST['About'] . "
        Message: " . $_POST['Message']; 

        if(mail($to, $subject, $content, 'From:' . $from)){
            echo '<p class="alert alert-success">Thank you for contacting us, your message has been sent.</p>'; 
        } else { 
           echo '<p class="alert alert-danger">There was a problem sending your message</p>'; 
        } 
    } else { 
        echo '<p class="alert alert-danger">' . $errors . '</p>'; 
    }
}
?>

The combined template

Here is the final template file with all the generated code included.

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

?>
<?php get_header(); ?>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST'){

    if (!isset($_POST['FirstName']) || !isset($_POST['SecondName']) || !isset($_POST['Email'])){

        $errors .= 'Please complete all the required fields.';
    }

    if ($_POST['FirstName'] != "") {
        $_POST['FirstName'] = filter_var($_POST['FirstName'], FILTER_SANITIZE_STRING);
        if ($_POST['FirstName'] == "") {
            $errors .= 'First Name is not valid.<br/>';
        }
    }

    if ($_POST['SecondName'] != "") {
        $_POST['SecondName'] = filter_var($_POST['SecondName'], FILTER_SANITIZE_STRING);
        if ($_POST['SecondName'] == "") {
            $errors .= 'Second Name is not valid.<br/>';
        }
    }

    if ($_POST['Email'] != "") {
        $email = filter_var($_POST['Email'], FILTER_SANITIZE_EMAIL);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors .= 'Email is not valid.<br/>';
        }
    }

    if ($_POST['Telephone'] != "") {
        $_POST['Telephone'] = filter_var($_POST['Telephone'], FILTER_SANITIZE_STRING);
        if ($_POST['Telephone'] == "") {
            $errors .= 'Telephone is not valid.<br/>';
        }
    }

    if ($_POST['About'] != "") {
        $_POST['About'] = filter_var($_POST['About'], FILTER_SANITIZE_STRING);
        if ($_POST['About'] == "") {
            $errors .= 'About is not valid.<br/>';
        }
    }

    if ($_POST['Message'] != "") {
        $_POST['Message'] = filter_var($_POST['Message'], FILTER_SANITIZE_STRING);
        if ($_POST['Message'] == "") {
            $errors .= 'Message is not valid.<br/>';
        }
    }

    if(!isset($errors)) {
        $to = 'you@yoursite.com';
        $from = $_POST['Email'];
        $subject = 'Contact Form Submission';
        $content = "
        First Name: " . $_POST['FirstName'] . "
        Second Name: " . $_POST['SecondName'] . "
        Email: " . $_POST['Email'] . "
        Telephone: " . $_POST['Telephone'] . "
        About: " . $_POST['About'] . " 
        Message: " . $_POST['Message'];

        if(mail($to, $subject, $content, 'From:' . $from)){
            echo '<p class="alert alert-success">Thank you for contacting us, your message has been sent.</p>';
        } else {
            echo '<p class="alert alert-danger">There was a problem sending your message</p>';
        }
    } else {
        echo '<p class="alert alert-danger">' . $errors . '</p>';
    }
}

?>

<form id="form" class="form" name="form" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">
    <h1>Get in touch</h1>
    <div class="form-content">
        <div class="intro"><p>Use the form below to get in touch!</p></div>
        <h2 class="section">Your Details</h2>
        <div id="section1">
            <div class="field"><div class="edit-options"><div class="edit"></div><div class="delete"></div></div><label for="FirstName">First Name</label><input type="text" id="FirstName" name="FirstName" required></div>
            <div class="field"><label for="SecondName">Second Name</label><input type="text" id="SecondName" name="SecondName" required></div>
            <div class="field"><label for="Email">Email</label><input type="email" id="Email" name="Email" required></div>
            <div class="field"><label for="Telephone">Telephone</label><input type="tel" id="Telephone" name="Telephone"></div>
        </div>
        <h2 class="section">Message</h2>
        <div id="section2">
            <div class="field"><label for="About">About</label><select id="About" name="About"><option value="general">General Enquiry</option><option value="service">Services</option><option value="product">Products</option></select></div>
            <div class="field"><textarea id="Message" name="Message" wrap="hard" required></textarea></div>
            <div class="field"><input type="submit" id="SubmitForm"></div>
        </div>
    </div>
</form>
<link href="http://fonts.googleapis.com/css?family=Roboto" id="google-font-selector" rel="stylesheet" type="text/css">

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Try it out!

You should now be able to browse to your page, view the form, submit it and receive an email notification with all the form contents. Note that your server will need the ability to send out emails with the PHP send_mail function, this will be available by most shared hosts.

Customise your forms with our code generator tool.

HTML5 Responsive Form Generator

David Bainbridge

Coveloping co-founder and regular contributor to the Coveloping blog. David is a contract web developer based in Bristol, UK also posting code snippets and tutorials on the Code Synthesis blog.

Coveloping Membership

Access to a range of developer tools, get your first month free

Start Your Free Trial

Don't miss out!

Sign up to our newsletter for the latest news from Coveloping

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Hi David,

    I set this up on a development site as I wanted to replace an outdated 'built in' contact form which I've been using for some client sites. All the fields data comes through just fine in the email notification with the exception of the actual message from the textarea.

    I copied the code directly so I'm not quite sure what's happening. Any ideas at all?

    Many thanks in advance.

    • Hi Mark, looks like 'message' was missing a name attribute and didn't have any form processing in the code example - thanks for letting me know - I've updated the code, that should work for you now.

  • Code Copied!