1. Code
  2. PHP

WordPress Error Handling With the WP_Error Class

Scroll to top
This post is part of a series called WordPress Error Handling.
WordPress Error Handling with WP_Error Class II

Even if you wear an S on your chest, when it comes to programming, errors will undoubtedly creep into your application. These errors are either caused by programmers as a result of code errors or by users who are unwilling to conform to the application or website constraints.

The errors caused by the end users are usually more serious than that of the programmers because the data or information entered by the user is unpredictable.

For example, in an email form field, instead of entering a valid email, the user might enter some other text. If the website lacks a solid error-handling mechanism, the user can gain unauthorized access to sensitive information.

Since user behavior can't be predicted, a website or application can be programmed to reject any invalid data entered by the user and inform the user that the data was invalid. This process is called error handling.

WordPress ships with a WP_Error class, which makes error handling within plugins and WordPress itself much easier.

Importance of Error Handling

Error handling is crucial in any application to ensure smooth execution and a good user experience. As a programmer, you must take care of error handling in your applications because it's important for identifying, managing, and resolving issues that may arise during application execution.

With the proper error handling in place, it improves the code quality, user experience, and security, which leads to robust and reliable applications.

Here are some of the key benefits of error handling:

Better User Experience

Error handling plays a very important role in enhancing the user experience of your applications. Instead of displaying raw error messages, blank white pages, or technical details to users, you can gracefully handle the errors that occurred during the execution of your code by presenting user-friendly messages or providing alternative actions.

Security

Proper error handling can significantly improve the security of your PHP applications. Instead of displaying detailed error messages, which may give a hint about your application internals to potential attackers, you can suppress these and display short and friendly error messages.

Solve Unknown Application Bugs

Errors and exceptions provide valuable information when something goes wrong in your PHP code execution. If you've logged them properly, you could audit these logs regularly to identify and solve any crucial errors that may have occurred on some specific actions taken by users in your application. Without properly logging these exceptions, it's almost impossible to identify these unknown bugs.

Improve the Overall Quality of Your Code

Errors and exceptions provide valuable information when something goes wrong in your PHP code. By tracking, analyzing, and solving recurring issues, you can gradually make your application more stable and secure.

Understanding the WP_Error Class

To start with, the WP_Error class consists of two properties and a handful of methods. These properties are used internally by the class, and you most likely won't need to access these properties directly since there are methods available to access the information you need.

WP_Error Class Properties

Below are the two class properties and what they do:

  • $errors is an array containing a list of errors.
  • $error_data is an array containing a list of data for error codes.

Before we examine the class methods, I would like to explain three terms that are used internally by the WP_Error class: code, message, and error data.

Don't worry if they're difficult to understand right now: things will become clearer as we examine code samples in the next section.

  • The code is the key for the error. Both the message and the error data are indexed by this key.
  • The message is a description of the error. It is saved to the errors class property, with the key specified in the code parameter.
  • The error data contains other data about the error. It is saved to the error_data property, also with the key specified in the code parameter.

Error codes are slugs that are used to identify each error in WordPress.

As per the official documentation:

The error codes used in WordPress are not integers, but strings, with any spaces between words replaced with underscores (example: an_error_code). The error codes used in WordPress are usually based on the error message associated with that code.

So that's it for the properties of the WP_Error class.

WP_Error Class Methods

In the previous section, we discussed the properties provided by the WP_Error class. In this section, we'll go through the class methods available in the WP_Error class.

The __construct Method

It's the constructor method, and it's used to initialize the WP_Error object. It accepts three arguments: $code, $message, and $data

The add Method

You can use it to either add an error or append an additional message to an existing error. It accepts three arguments: $code, $message, and $data

The add_data Method

It's used to add data to an error with the given code. Basically, it adds additional information about the error, which can be useful to understand the error. It takes two parameters: $data and $key.

The copy_errors Method

It's used to copy errors from one WP_Error instance to another instance. It takes two arguments, the $from WP_Error object and the $to WP_Error object.

The export_to Method

It's used to export the errors in the current WP_Error object into the given one in the first argument $error.

The get_all_error_data Method

It's used to get all the error data for a given error code in the first argument $code. It retrieves the data in the order in which it was added.

The get_error_code Method

It's used to retrieve the error code of the first error in the WP_Error object.

The get_error_codes Method

It's used to return an array containing all the error codes present in the WP_Error object.

The get_error_data Method

It's used to retrieve the additional data associated with the first error in the WP_Error object.

The get_error_message Method

It's used to retrieve the error message of the first error in the WP_Error object. If you pass the $code in the first argument, it returns the first message available for the given error code.

The get_error_messages Method

It returns an array containing all the error messages present in the WP_Error object. If you pass the $code in the first argument, it returns error messages for the given error code.

The has_errors Method

It's used to check if the WP_Error object has any errors.

The merge_from Method

It's used to merge errors from the WP_Error object given in the first argument to the current WP_Error object.

The remove Method

It's used to remove all the error messages associated with the given error code, along with any other error data for that code.

How the WP_Error Class Works

To use the WP_Error class for error handling, you need to instantiate the class in the first place. Then, you can use class methods to manipulate the WP_Error object.

How to Add Data to the WP_Error Object

Let's see how you can initialize the WP_Error object.

1
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly' );

Examining the structure of the $my_error object via print_r() reveals:

1
WP_Error Object
2
(
3
    [errors] => Array
4
        (
5
            [toy] => Array
6
                (
7
                    [0] => my favorite toy is dolly
8
                )
9
        )
10
    [error_data] => Array
11
        (
12
        )
13
)

You'll have noticed that the error we defined is stored in the errors class property, while the error_data property has no data yet.

Passing a third argument while creating the WP_Error object fills the $data property, with the $code (first argument) being the array key and the third argument $data being the array value.

1
<?php
2
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly', 'my best' );
3
print_r( $my_error );
4
?>

Now, let's examine the structure of the WP_Error object.

1
WP_Error Object
2
(
3
    [errors] => Array
4
        (
5
            [toy] => Array
6
                (
7
                    [0] => my favorite toy is dolly
8
                )
9
        )
10
    [error_data] => Array
11
        (
12
            [toy] => my best
13
        )
14
)

To add or append more error messages to the list of errors, we use the add method, which accepts $code, $message, and $data as arguments.

1
<?php
2
$my_error = new WP_Error( 'toy', 'my favorite toy is dolly', 'best toy' );
3
$my_error->add( 'game', 'my favorite game console is PS4' );
4
?>

Passing a third argument (mixed data-type) to the add method adds data to the error code.

1
<?php
2
$my_error->add( 'game', 'my favorite game console is PS4', 'best game' );
3
?>

Using print_r() again, let's view the structure and information of our $my_error WP_Error object.

1
WP_Error Object
2
(
3
    [errors] => Array
4
        (
5
            [toy] => Array
6
                (
7
                    [0] => my favorite toy is dolly
8
                )
9
            [game] => Array
10
                (
11
                    [0] => my favorite game console is PS4
12
                )
13
        )
14
    [error_data] => Array
15
        (
16
            [toy] => best toy
17
            [game] => best game
18
        )
19
)

The add_data() method is used to add data for the given error code.

1
$my_error->add_data( 'my best teacher is Uncle Sam', 'teacher' );

So far, we have learned how to instantiate the WP_Error object and add error messages and data using various methods. In the next section, we'll see how to retrieve the error messages, code, and data.

How to Retrieve Data from the WP_Error Object

You can use the get_error_codes() method to return an array of all error codes.

1
print_r( $my_error->get_error_codes() );
2
3
/* 

4
Output:

5


6
Array

7
(

8
    [0] => toy

9
    [1] => game

10
)

11
*/

On the other hand, the get_error_code() method returns only the first error code.

1
print_r( $my_error->get_error_code() ); 
2
// Output: toy

The get_error_messages() method retrieves all the error messages when the code argument is absent, but when the $code argument is passed, it returns the error messages that match it.

1
print_r( $my_error->get_error_messages() );
2
3
/* Output:

4
Array

5
(

6
    [0] => my favorite toy is dolly

7
    [1] => my favorite game console is PS4

8
)

9
*/

When you pass the first argument, it looks like this:

1
print_r( $my_error->get_error_messages( 'game' ) );
2
3
/* Output:

4
Array

5
(

6
    [0] => my favorite game console is PS4

7
)

8
*/

The get_error_message() returns a single error message that matches the code. If the $code argument is not passed, it returns the first error message.

1
print_r( $my_error->get_error_message() );
2
// Output: my favorite toy is dolly

The get_error_data() returns the data for the first error code.

1
print_r( $my_error->get_error_data() );
2
// Output: best toy

On the other hand, when you pass the first argument:

1
print_r( $my_error->get_error_data( 'teacher' ) );
2
// Output: my best teacher is Uncle Sam

When you're building a WordPress plugin, you might want to check if a variable is an instance of the WP_Error object. This is where the is_wp_error() method comes in handy.

Also, you might want to make sure that the WP_Error object doesn't contain any error message before any action is processed. For example, the code snippet below checks to make sure the $my_error object doesn't contain any errors.

1
if ( 1 > count( $my_error->get_error_messages() ) ) {
2
    echo "No error, we're good to go";
3
}

How to Use WP_Error in a Real-World Situation

In this section, we'll explore how you can use the WP_Error class in a real-world scenario.

Let's assume you have a custom survey form with fields such as email, name, and so on. Our goal is to validate these form fields before submission and display any errors using the WP_Error class.

Let's examine the following code snippet.

1
<?php 
2
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
3
  $error = new WP_Error();
4
5
  $email = $_POST['email'] ?? '';
6
  $name = $_POST['name'] ?? '';
7
8
  if (empty($email)) {
9
      $error->add('empty','Email is required field.');
10
  }
11
12
  if (!is_email($email)) {
13
      $error->add('invalid', 'Please enter valid email.');
14
  }
15
16
  if (empty($name)) {
17
      $error->add('empty','Name is required field.');
18
  }
19
20
  if (count($error->get_error_codes())) {
21
      echo '<div>Please correct the following errors.</div>';
22
        echo '<ul>';
23
      echo '<li>' . implode( '</li><li>', $error->get_error_messages() ) . '</li>';
24
      echo '</ul>';
25
  } else {
26
      // continue with the submission data and redirect

27
  }
28
}
29
30

First, this code checks if the form has been submitted using the HTTP POST method. Next, we create a new instance of the WP_Error class.

Moving ahead, we retrieve the submitted values for the email and name fields using the $_POST superglobal array and attempt to validate them. If there are any errors, we use the add method of the WP_Error class to add errors to the $error object.

Finally, we check if any errors have been added to the $error object using the get_error_codes method of the WP_Error class. In case of any errors, we display those errors using the get_error_messages method. If there are no errors, we proceed with further operations such as inserting the record in a database and so on.

Conclusion

We've just learned about the WP_Error object in WordPress. We learned how to create a WP_Error object and how to add error messages to it. This way, we can collect lots of information about the mistake and where it happened, which makes it easier to fix.

We saw how to use functions like get_error_message(), get_error_code(), and get_error_data() to get more information about an error. By learning these, you can build stronger WordPress websites and deal with mistakes more easily when they happen.

Remember, making mistakes when coding is normal. WP_Error helps you understand and manage these mistakes to improve your website.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.