WP_Error: return errors the WordPress way
A function that returns false on failure tells the caller that something went wrong, but not what. WordPress has its own error object for this, WP_Error: it carries an error code, a message and optional data, and it can hold several errors at once. Core functions such as wp_insert_post(), wp_insert_user() and wp_remote_get() return it, and the REST API turns it into an error response automatically.
Problem: A plugin’s import function calls several WordPress functions in a row; when one of them fails, the caller gets false and cannot show a useful message or log which step failed.
Solution: Return a WP_Error from every step that can fail, check results with is_wp_error(), collect several validation errors in one object, and return the object from REST callbacks with a status in its data.
Creating and reading errors
<?php
$error = new WP_Error(
'ha_import_failed', // code: a machine-readable string
__( 'The import failed.', 'textdomain' ), // message for humans
array( 'row' => 12 ) // optional data of any type
);
$error->add( 'ha_missing_role', __( 'No role was given.', 'textdomain' ) );
$error->get_error_code(); // 'ha_import_failed' (the first code)
$error->get_error_codes(); // both codes
$error->get_error_message(); // the first message
$error->get_error_messages(); // all messages
$error->get_error_data(); // array( 'row' => 12 )
Checking results
<?php
$user_id = wp_insert_user( $userdata );
if ( is_wp_error( $user_id ) ) {
error_log( 'User import: ' . $user_id->get_error_message() );
return $user_id; // pass it on, the caller checks with is_wp_error() too
}
Always use is_wp_error(): a WP_Error object is “truthy”, so if ( ! $result ) does not catch it.
Collecting validation errors
To show all problems of a form at once instead of the first one:
<?php
function ha_validate_import_row( array $row ) {
$errors = new WP_Error();
if ( empty( $row['email'] ) || ! is_email( $row['email'] ) ) {
$errors->add( 'invalid_email', __( 'Invalid email address.', 'textdomain' ) );
}
if ( empty( $row['username'] ) ) {
$errors->add( 'missing_username', __( 'The username is required.', 'textdomain' ) );
}
return $errors->has_errors() ? $errors : true;
}
$valid = ha_validate_import_row( $row );
if ( is_wp_error( $valid ) ) {
foreach ( $valid->get_error_messages() as $message ) {
echo '<p class="error">' . esc_html( $message ) . '</p>';
}
}
has_errors() exists since WordPress 5.1; on older versions check $errors->get_error_codes().
In the REST API
A REST callback can simply return a WP_Error. The API sends the code and message as JSON, and the HTTP status from the status key of the data:
<?php
add_action( 'rest_api_init', function () {
register_rest_route( 'ha/v1', '/import', array(
'methods' => 'POST',
'permission_callback' => function () {
return current_user_can( 'manage_options' );
},
'callback' => function ( WP_REST_Request $request ) {
$valid = ha_validate_import_row( $request->get_json_params() );
if ( is_wp_error( $valid ) ) {
$valid->add_data( array( 'status' => 422 ) );
return $valid; // {"code":"invalid_email","message":"...","data":{"status":422}}
}
return array( 'imported' => true );
},
) );
} );
Without a status, the response gets status 500.
NOTE: Use your own prefix in error codes (ha_import_failed, not failed) so they do not clash with codes from core or other plugins, and keep codes stable: other code may check for them with get_error_code(), while messages can change and be translated.