WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Class Reference/WP Error

Description

WP_Error is a class that makes error handling within plugins and WordPress itself much easier.

Instances of WP_Error store error codes and messages representing one or more errors, and whether or not a variable is an instance of WP_Error can be determined using the is_wp_error() function.

Methods and Properties

Properties

$errors
Array containing the list of errors.
$error_data
Array containing the list of data for error codes.

Note: Since 4.0, these properties are private, see [28511].

Methods

__construct( $code = '', $message = '', $data = '' )
Sets up the error message. All parameters are optional, and if the $code parameter is empty, the other parameters will be ignored. When the $code parameter is set to a non-empty value, the $message will be used even if it is empty, but the $data parameter will be used only if it is not empty. It is possible to add multiple messages to the same code by using other methods in the class.
get_error_codes()
Retrieve all error codes. Access public, returns array List of error codes, if available.
get_error_code()
Retrieve first error code available. Access public, returns string, int or Empty if there is no error codes
get_error_messages($code)
Retrieve all error messages or error messages matching code. Access public, returns an array of error strings on success, or empty array on failure (if using code parameter)
get_error_message($code)
Get single error message. This will get the first message available for the code. If no code is given then the first code available will be used. Returns an error string.
get_error_data($code)
Retrieve error data for error code. Returns mixed or null, if no errors.
add($code, $message, $data)
Append more error messages to list of error messages. No return.
add_data($data, $code)
Add data for error code. The error code can only contain one error data. No return.
remove($code)
Remove any messages and data associated with an error code. No return.

Example

function doer_of_stuff() {
    return new WP_Error( 'broke', __( "I've fallen and can't get up", "my_textdomain" ) );
}

$return = doer_of_stuff();
if( is_wp_error( $return ) ) {
    echo $return->get_error_message();
}

Source

WP_Error is located in wp-includes/class-wp-error.php

Change Log

  • In 4.1.0: Added remove() method.
  • In 4.0.0: Errors and data arrays became private, added magic access methods for backwards compatibility.
  • Introduced in 2.1.0

Related

  • see is_wp_error() for more information on trapping for errors (particularly useful when faced with the dreaded 'Catchable fatal error: Object of class WP_Error could not be converted to string')
See also index of Class Reference and index of Function Reference.