1. Code
  2. WordPress
  3. Plugin Development

WordPress Error Handling with WP_Error Class II

In this second part of the series on handling errors in WordPress using WP_Error, we will be building a contact-form plugin to demonstrate this is done.
Scroll to top
5 min read
This post is part of a series called WordPress Error Handling.
WordPress Error Handling With the WP_Error Class

In the first part of this series on handling errors in WordPress with the WP_Error class, we took a look at an introduction of the PHP class, we examined the class properties and methods and their roles and functions complemented by code examples.

In this final part of the series, we will be building a fairly simple contact form plugin to demonstrate how to handle errors in plugin development. The contact-form plugin will have shortcode and template tag support so it can be implemented in posts and pages using the former and in a theme using the latter. 

Contact-Form Plugin Development

The contact form will consist of five form fields - four input elements and a textarea element.

I'm sure you are familiar with all the contact-form field. Note that when an email is sent via the contact-form, the phone number get appended to the message. This is evident in the send_mail function.

Let's get started coding the plugin. First the plugin header:

1
<?php
2
/*

3
 Plugin Name: Contact Form Lite

4
 Plugin URI: https://code.tutsplus.com

5
 Description: Easy contact form plugin

6
 Author: Agbonghama Collins

7
 Author URI: http://tech4sky.com

8
 */

The plugin will consist of five PHP functions as outlined below.

  1. contact_html_form() will contain the HTML form code of the plugin.
  2. validate_form() handles the plugin error. we will see error handling using WP_Error in action in this function.
  3. send_mail() handles the sending of email.
  4. contact_form_function() brings together and process the above functions
  5. contact_form_shortcode() is the shortcode callback function.

The HTML form code of the plugin contained in contact_html_form() function  is as follows.

1
function contact_html_form() {
2
    global $name, $email, $phone_number, $subject, $message;
3
    
4
	echo '<form action="' . get_permalink() . '" method="post">

5
	

6
	<label for="name">Name <strong>*</strong></label>

7
	<input type="text" name="sender_name" value="' . ( isset( $_POST['sender_name'] ) ? $name : null ) . '" />

8
	

9
	<div>

10
	<label for="email">Email <strong>*</strong></label>

11
	<input type="text" name="sender_email" value="' . ( isset( $_POST['sender_email'] ) ? $email : null ) . '" />

12
	</div>

13
	

14
	<div>

15
	<label for="phonenumber">Phone Number <strong>*</strong></label>

16
	<input type="text" name="sender_phonenumber" value="' . ( isset( $_POST['sender_phonenumber'] ) ? $phone_number : null ) . '" />

17
	</div>

18
	

19
	<div>

20
	<label for="subject">Subject <strong>*</strong></label>

21
	<input type="text" name="email_subject" value="' . ( isset( $_POST['email_subject'] ) ? $subject : null ) . '" />

22
	</div>

23
	

24
	<div>

25
	<label for="message">Message <strong>*</strong></label>

26
	<textarea name="email_message">' . ( isset( $_POST['email_message'] ) ? $message : null ) . '</textarea>

27
	</div>

28
	

29
	<div>

30
	<input type="submit" name="send_message" value="Send" />

31
	</div>

32
	</form>';
33
}

Next is the error handling function validate_form().

The following are the constraint to be implemented by the plugin which will be enforced by the error handling function.

Note that:

  • no field should be left empty
  • the name field must contain an alphabetic character
  • the email should be valid
  • the phone number should be numeric

The validate_form() function will accept the form fields as it argument so it can validate the form data for errors. Below is the code for the error-handling function that enforces the above plugin constraint fully commented so you'll easily trace its code

1
function validate_form( $name, $email, $phone_number, $subject, $message ) {
2
3
    // Make the WP_Error object global    

4
	global $form_error;
5
	
6
	// instantiate the class

7
	$form_error = new WP_Error;
8
	
9
	// If any field is left empty, add the error message to the error object

10
	if ( empty( $name ) || empty( $email ) || empty( $phone_number ) || empty( $subject ) || empty( $message ) ) {
11
		$form_error->add( 'field', 'No field should be left empty' );
12
	}
13
	
14
	// if the name field isn't alphabetic, add the error message

15
	if ( ! ctype_alpha( $name ) ) {
16
		$form_error->add( 'invalid_name', 'Invalid name entered' );
17
	}
18
	
19
	// Check if the email is valid

20
	if ( ! is_email( $email ) ) {
21
		$form_error->add( 'invalid_email', 'Email is not valid' );
22
	}
23
	
24
	// if phone number isn't numeric, throw an error

25
	if ( ! is_numeric( $phone_number ) ) {
26
		$form_error->add( 'phone_number', 'Phone-number is not numbers' );
27
	}
28
	
29
	// if $form_error is WordPress Error, loop through the error object

30
	// and echo the error

31
	if ( is_wp_error( $form_error ) ) {
32
		foreach ( $form_error->get_error_messages() as $error ) {
33
			echo '<div>';
34
			echo '<strong>ERROR</strong>:';
35
			echo $error . '<br/>';
36
			echo '</div>';
37
		}
38
	}
39
40
}

The send_mail function handles the email sending.

1
function send_mail( $name, $email, $phone_number, $subject, $message ) {
2
    global $form_error;
3
    
4
	// Ensure WP_Error object ($form_error) contain no error

5
	if ( 1 > count( $form_error->get_error_messages() ) ) {
6
			
7
		// sanitize user form input

8
		$name 			= 	sanitize_text_field( $name );
9
		$email 			= 	sanitize_email( $email );
10
		$phone_number 	= 	esc_attr( $phone_number );
11
		$subject 		= 	sanitize_text_field( $subject );
12
		$message 		= 	esc_textarea( $message );
13
		
14
		// set the variable argument use by the wp_mail

15
		$message 	.= 	'\n Phone Number:' . $phone_number;
16
		$to 		= 	'admin@tech4sky.com';
17
		$headers 	= 	"From: $name <$email>" . "\r\n";
18
		
19
		// If email has been process for sending, display a success message	

20
		if ( wp_mail( $to, $subject, $message, $headers ) ) {
21
			echo "Thanks for contacting me.";
22
		}
23
24
	}
25
}

Let's take a look at what's going on in the send_mail function.

First, the $form_error object is made global so it can be accessed outside the function scope. A check is made to ensure the $form_error object contains no error message. If true, the contact form input is sanitized.

The $to variable stores the email address the message sent via the contact form will be sent to. On a standard contact-form plugin, the variable should contain the WordPress administrator email retrieve from the database or from the plugin settings.

Take note of how the phone number get concatenated to the message.

Finally, the wp_mail function sends the mail. 

The contact_form_function() function processes the function and also serve as the plugin template tag.

1
function contact_form_function() {
2
    global $name, $email, $phone_number, $subject, $message;
3
	if ( isset($_POST['send_message']) ) {
4
		// Get the form data

5
		$name 			= 	$_POST['sender_name'];
6
		$email 			= 	$_POST['sender_email'];
7
		$phone_number 	= 	$_POST['sender_phonenumber'];
8
		$subject 		= 	$_POST['email_subject'];
9
		$message 		= 	$_POST['email_message'];
10
		
11
		// validate the user form input

12
		validate_form( $name, $email, $phone_number, $subject, $message );
13
		
14
		// send the mail

15
		send_mail( $name, $email, $phone_number, $subject, $message );
16
17
	}
18
	
19
	// display the contact form

20
	contact_html_form();
21
22
}

Remember the contact-form plugin is going to have shortcode support. Below is the shortcode call-back function together with the add_shortcode function that registers the shortcode.

1
// Register a new shortcode: [cf_contact_form]

2
add_shortcode('cf_contact_form', 'contact_form_shortcode');
3
4
// Shortcode callback function

5
function contact_form_shortcode() {
6
    ob_start();
7
    contact_form_function();
8
    return ob_get_clean();
9
}

Using The Plugin

Use the shortcode [cf_contact_form] to include the contact-form in a post or page.
To include the contact-form in your theme, use the template tag <?php contact_form_function(); ?> .

Summary

In this article, we took a look at how to use the WP_Error class to handle errors in plugins. I also showed us a practical use-case on how to handle errors in plugin using the class. You can find the plugin file attached to this article.

Happy Coding!