How I created my contact page without Contact Form 7

How I created my contact page without Contact Form 7

This blog post was written by and published 28th April 2016.

Why I removed Contact Form 7

As a front-end developer with fairly limited PHP experience I understand it can be daunting when thinking of coding your own custom contact form – its not something I’ve done before and I wasn’t really sure where to start.

Its very easy to just install a plugin to add this functionality and Contact Form 7 is one of the most popular. It’s main problem (in my opinion) is that it loads it’s CSS & JS files on every page, it’s fair to think that these files would only be loaded on the pages including forms, but you’d be wrong for thinking that.

Contact Form 7 loads it’s files (1 CSS and 2 JS) on every page of the site – adding unneeded bloat to your overall page size and additional resource calls which slow down your loading time. I knew by removing this plugin I could reduce server calls, page size and improve the speed of my site.

How I built the contact form page template

I decided when building this theme to code my own contact form template which would include the needed scripts only on pages using the contact template.

I hard coded the form elements beneath the normal <?php the_content() ?> tag so I could still edit page content using the WordPress admin. I then and added styles to my theme’s stylesheet, I used 1.38kb of CSS code to style the form so there was no need for a separate stylesheet (like the one used by Contact Form 7).

The PHP script I used to submit the form

Once I had my form looking as I designed it I began researching the PHP needed to submit the form and email the information to my address. I found this guide and used the PHP script they provided and modified it to suit my form, I also added some jQuery (im planning on converting this to native Javascript when I get chance), to validate the form before submitting and display error messages where needed.

With the code provide you can add basic inline styling or if you want to add more complex styles you can also read the next step to see how I styled the email response to include a header, footer and more formatted area for the message contents.

Heres the complete contact form template including PHP, HTML & JS

Expand this code block<?php 
	//response generation function
	$response = "";
	//function to generate response
	function my_contact_form_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['input-name'];
	$email = $_POST['input-email'];
	$website = $_POST['input-website'];
	$budget = $_POST['input-budget'];
	$their_message = $_POST['input-message'];
	$human = $_POST['message_human'];
	// message contents
	$message = "<h1 style='color: #62c8d0;'>Someone's sent a message!</h1>";

	$message .= "<strong>Their name:</strong> $name\n";
	$message .= "<br/>";
	$message .= "<strong>Their email address:</strong>$email\n";
	$message .= "<br/>";
	$message .= "<strong>Their website:</strong> $website\n";
	$message .= "<br/>";
	$message .= "<strong>Their budget:</strong> $budget\n";
	$message .= "<br/>";
	$message .= "<strong>Their message:</strong> $their_message\n";
	$message .= "<br/>";
	// send email to wordpress admin:
	$to = get_option('admin_email');
	// uncomment to also send email to user
	//$to .= ", " . $email;
	// set email subject
	$subject = "Message from";
	// set from/reply to
	$headers = 'From: '. $email . "\r\n" .
	'Reply-To: ' . $email . "\r\n";
	if(!$human == 0){
		if($human != 2) my_contact_form_generate_response("error", $not_human); //not human!
		else {
		//validate email
		if(!filter_var($email, FILTER_VALIDATE_EMAIL))
			my_contact_form_generate_response("error", $email_invalid);
			else //email is valid
				//validate presence of name and message
				if(empty($name) || empty($message)){
				  my_contact_form_generate_response("error", $missing_content);
				else //ready to go!
				  // send message
				  $sent = wp_mail($to, $subject, $message, $headers);
				  header('Location: /contact-me/thanks-for-messaging-me/');
				  if($sent) my_contact_form_generate_response("success", $message_sent); //message sent!
				  else my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
	else if ($_POST['submitted']) my_contact_form_generate_response("error", $missing_content);
	/* Template Name: Contact Form */

    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <article class="boxed">
        <h1 class="pagetitle align-center"><?php the_title(); ?></h1>
        <?php the_content(); ?>
        <!-- FORM START HERE -->
        <!-- ////////////////////////////// -->
        <div id="respond">
            <?php echo $response; ?>
            <form action="<?php the_permalink(); ?>" method="post" id="messageForm">
			    <div class="one-half first">
			      <div class="input-container">
			        <input type="text" id="input-name" name="input-name" class="input-name">
			        <label for="input-name" unselectable="on">Your name</label>
			        <i class="fa fa-user"></i>
			         <p class="error">Please let me know your name</p>
			      <div class="input-container">
			        <input type="text" id="input-website" name="input-website" class="input-website">
			        <label for="input-website" unselectable="on">Website <small>(if you have one)</small></label>
			        <i class="fa fa-globe"></i>
			    <div class="one-half last">
			      <div class="input-container">
			        <input type="email" id="input-email" name="input-email" class="input-email">
			        <label for="input-email" unselectable="on">Your Email</label>
			        <i class="fa fa-envelope-o"></i>
			        <p class="error">Please let me know your email address</p>
			      <div class="input-container">
			        <input type="tel" id="input-budget" name="input-budget" class="input-budget">
			        <label for="input-budget" unselectable="on">Your Budget</label>
			        <i class="fa fa-balance-scale"></i>
			    <div class="clear"></div>
			    <div class="input-container message-box">
			        <textarea rows="6" id="input-message" name="input-message" class="input-message"></textarea><label for="input-message" unselectable="on" class="input-message">Your message</label>
			        <i class="fa fa-comment"></i>
			        <p class="error">Please enter your message</p>
			    <div class="question">
					<label for="message_human">Some simple maths to prove your human:  <input type="text" style="width: 60px;" name="message_human" id="input-human"> + 3 = 5</label>
					<div class="clear"></div>
					<p class="error">Please complete this maths question so I know you're not a robot</p>
			    <!-- Submit Button -->
			    <a class="calltoaction" id="quoteMessage">Submit your message</a>
			<!-- FORM END HERE -->
			<!-- ////////////////////////////// -->
    <?php endwhile; ?>
    <?php endif; ?>
		    // submit form
			$("#quoteMessage").on("click", function(){
				// check if form is valid				
				var isValid = validateForm();
				// if valid submit message
					console.log("form submitted")
				} else {
					console.log("form error")
			// validate form function
			function validateForm(){
				var nameValid = false;
				var emailValid = false;
				var messageValid = false;
				var humanValid = false;
				// if input empty set as invalid and show error otherwise validated true			
					nameValid = false;
					$("#input-name").siblings(".error").css("display", "inline-block");
				} else {
					nameValid = true;
					console.log("name valid")
					emailValid = false;
					$("#input-email").siblings(".error").css("display", "inline-block");
				} else {
					emailValid = true;
					console.log("email valid")
					messageValid = false;
					$("#input-message").siblings(".error").css("display", "inline-block");
				} else {
					messageValid = true;
					console.log("message valid")
				if($("#input-human").val() == "2"){
					humanValid = true;
					console.log("human valid")
				} else {
					humanValid = false;
					$("#input-human").parent().siblings(".error").css("display", "inline-block");
				// if everything is valid - validation returns true
					nameValid &&
					emailValid &&
					messageValid &&
					return true;
					console.log("validation: true")
				} else {
					return false;
					console.log("validation: false")
			// text input hide errors on keyup
			$("#input-name").on("keyup", function(){
				$(this).siblings(".error").css("display", "");
			$("#input-email").on("keyup", function(){
				$(this).siblings(".error").css("display", "");
			$("#input-message").on("keyup", function(){
				$(this).siblings(".error").css("display", "");
			$("#input-human").on("keyup", function(){
				if($(this).val() == "2"){
					$(this).parent().siblings(".error").css("display", "");

<?php get_footer(); ?>

How I built the formatted HTML email response

I was pleased my form was submitting, but now I wanted to add style to the plain text email response. I decided the best way to do this would be to setup HTML files for the header and footer section of my HTML email. I used a simple layout and inserted the header/footer templates into the message using file_get_contents(TEMPLATEPATH . 'YOUR-HTML-TEMPLATE.html');

These templates include some a basic HTML table framework styled with CSS inline at the top of the header template.

Updated message code to include templates:

	// message contents
	$message = file_get_contents(TEMPLATEPATH . '/includes/email-header.html');
	$message .= "<h1 style='color: #62c8d0;'>Someone's sent a message!</h1>";

	$message .= "<strong>Their name:</strong> $name\n";
	$message .= "<br/>";
	$message .= "<strong>Their email address:</strong>$email\n";
	$message .= "<br/>";
	$message .= "<strong>Their website:</strong> $website\n";
	$message .= "<br/>";
	$message .= "<strong>Their budget:</strong> $budget\n";
	$message .= "<br/>";
	$message .= "<strong>Their message:</strong> $their_message\n";

	$message .= file_get_contents(TEMPLATEPATH . '/includes/email-footer.html');

My Conclusion

It works, but it may not be the best solution. I’ve build a custom WordPress contact page template which will send a (rather simple) styled email and removed Contact Form 7. Doing this has improved the speed of my website and given me more control over my contact forms.

In an ideal world I would have a single email template with variables which would populate the relevant data from the form. Doing this I could build a more complicate HTML email without adding additional mess to my template page. If you know how I could improve this template or script please let me know below.