Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

How To Build a WordPress Contact Form

One feature common to almost every website in the world is the contact form. It can be used to collect feedback, complaints or useful information from website clients and users.

A typical contact form consists of the following fields – sender name, sender email address, email subject and the message.

Create Contact Form WordPress

In this tutorial, you will learn to build a simple contact form with a WordPress plugin.

Contact Form PHP Class Synopsis

The contact form PHP class will consist of a property and six methods (known as “functions” in procedural programming).

[php]
<?php
class Designmodo_contact_form {
private $form_errors = array();

function __construct() {
// …
}

static public function form() {
// …
}

public function validate_form() {
// …
}

public function send_email() {
// …
}

public function process_functions() {
// …
}

public function shortcode() {
// …
}

}
[/php]

The private property $form_errors is an array that will store all the errors that will be generated by the contact form. I will explain what each class method does as we walk through the coding of the contact form plugin.

Coding the Contact Form Plugin

Like other WordPress plugins, the header is the first thing to go into the plugin file. Below is our contact form header followed by the class declaration and property.

[php]
<?php

/*
Plugin Name: Designmodo Contact Form
Plugin URI: https://designmodo.com
Description: Simple Contact form plugin that just work
Version: 1.0
Author: Agbonghama Collins
Author URI:
*/

class Designmodo_contact_form {

private $form_errors = array();
[/php]

The contact form will be embedded in WordPress via shortcode [contact_form_dm].

The magic __construct() method handles the registration of the shortcode so it is recognizable by WordPress.

[php]
function __construct() {
// Register a new shortcode
add_shortcode(‘contact_form_dm’, array($this, ‘shortcode’));
}
[/php]

The contact form HTML code will be in the static form() method.

[php]
static public function form() {
echo ‘<form action="’ . $_SERVER[‘REQUEST_URI’] . ‘" method="post">’;
echo ‘<p>’;
echo ‘Your Name (required) <br/>’;
echo ‘<input type="text" name="your-name" value="’ . $_POST["your-name"] . ‘" size="40" />’;
echo ‘</p>’;
echo ‘<p>’;
echo ‘Your Email (required) <br/>’;
echo ‘<input type="text" name="your-email" value="’ . $_POST["your-email"] . ‘" size="40" />’;
echo ‘</p>’;
echo ‘<p>’;
echo ‘Subject (required) <br/>’;
echo ‘<input type="text" name="your-subject" value="’ . $_POST["your-subject"] . ‘" size="40" />’;
echo ‘</p>’;
echo ‘<p>’;
echo ‘Your Message (required) <br/>’;
echo ‘<textarea rows="10" cols="35" name="your-message">’ . $_POST["your-message"] . ‘</textarea>’;
echo ‘</p>’;
echo ‘<p><input type="submit" name="form-submitted" value="Send"></p>’;
echo ‘</form>’;
}
[/php]

The validate_form method which accept the contact form values as it argument, will validate and ensure that:

  • No form field is unfilled or empty.
  • The sender name is not less than four characters.
  • The sender email is valid

To keep things simple and succinct, we will stick to the above validation rule. Below is the code for the validate_form method.

[php]
public function validate_form( $name, $email, $subject, $message ) {

// If any field is left empty, add the error message to the error array
if ( empty($name) || empty($email) || empty($subject) || empty($message) ) {
array_push( $this->form_errors, ‘No field should be left empty’ );
}

// if the name field isn’t alphabetic, add the error message
if ( strlen($name) < 4 ) {
array_push( $this->form_errors, ‘Name should be at least 4 characters’ );
}

// Check if the email is valid
if ( !is_email($email) ) {
array_push( $this->form_errors, ‘Email is not valid’ );
}
}
[/php]

The send_email() method sanitize and send the mail to the administrator email address.

[php]
public function send_email($name, $email, $subject, $message) {

// Ensure the error array ($form_errors) contain no error
if ( count($this->form_errors) < 1 ) {

// sanitize form values
$name = sanitize_text_field($name);
$email = sanitize_email($email);
$subject = sanitize_text_field($subject);
$message = esc_textarea($message);

// get the blog administrator’s email address
$to = get_option(‘admin_email’);

$headers = "From: $name <$email>" . "\r\n";

// If email has been process for sending, display a success message
if ( wp_mail($to, $subject, $message, $headers) )
echo ‘<div style="background: #3b5998; color:#fff; padding:2px;margin:2px">’;
echo ‘Thanks for contacting me, expect a response soon.’;
echo ‘</div>’;
}
}
[/php]

Take note, mail will be sent to the blog administrator or owner’s email address programmatically retrieved by the WordPress get_option function. The send_email() method ensure there isn’t any contact-form generated error before sending the email.

Next is the process_functions method. This method call and process the form, validate_form, send_email methods.

[php]
public function process_functions() {
if ( isset($_POST[‘form-submitted’]) ) {

// call validate_form() to validate the form values
$this->validate_form($_POST[‘your-name’], $_POST[‘your-email’], $_POST[‘your-subject’], $_POST[‘your-message’]);

// display form error if it exist
if (is_array($this->form_errors)) {
foreach ($this->form_errors as $error) {
echo ‘<div>’;
echo ‘<strong>ERROR</strong>:’;
echo $error . ‘<br/>’;
echo ‘</div>’;
}
}
}

$this->send_email( $_POST[‘your-name’], $_POST[‘your-email’], $_POST[‘your-subject’], $_POST[‘your-message’] );

self::form();
}
[/php]

Firstly, the method check if the contact-form has been submitted. If true, it call the validate_form to validate the form values and display the form generated message. The send_email is also called to send the email to the administrator.

Finally, the form to display the contact-form HTML form.

Earlier, we added a add_shortcode inside the magic __construct method to register the plugin shortcode to WordPress

[php]
add_shortcode(‘contact_form_dm’, array($this, ‘shortcode’));
[/php]

The second argument passed to the function is the shortcode callback method shortcode(), which is called when the shortcode is used.

[php]
public function shortcode() {
ob_start();
$this->process_functions();
return ob_get_clean();
}

}
[/php]

The class would be useless if it isn’t instantiated. Finally, we instantiate the class to put it to work.

[php]
new Designmodo_contact_form;
[/php]

How To Use the Contact Form Plugin

To embed the contact form in WordPress posts or pages, use the shortcut [contact_form_dm], while in a theme template, use the code below:

[php]
<?php echo do_shortcode(‘[contact_form_dm]’); ?>
[/php]

Below is a screenshot depicting a message has been successfully sent via the contact form.

Contact form

Conclusion

A lot of contact form plugins in the WordPress plugin repository are quite heavy and bloated. If you have been considering rolling out your own, this tutorial showed how to build a simple contact form.
[emaillocker]
Here is the link to the designmodo contact-form plugin just in-case you want to use in your WordPress site and also study the code to learn how it works.
[/emaillocker]
If you have any questions, or suggestions for code improvement, let me know in the comments.