Using WordPress ‘is_wp_error()’ PHP function

The is_wp_error() WordPress PHP function checks whether the given variable is a WordPress Error.

Usage

is_wp_error( $thing );

Example:
Input: $result
Output: true or false

Parameters

  • $thing (mixed) – The variable to check if it’s an instance of the WP_Error class.

More information

See WordPress Developer Resources: is_wp_error()

Related resource: The WP_Error class

Examples

Basic usage

Checking if a variable is a WordPress error and displaying an error message if it is.

$result = some_function_that_might_return_error();

if ( is_wp_error( $result ) ) {
    $error_string = $result->get_error_message();
    echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
}

Inserting a user and handling errors

Creating a new user with wp_insert_user() and handling errors using is_wp_error().

$email = '[email protected]';
$userdata = array(
    'user_login' => $email,
    'user_email' => $email,
);

$user_id = wp_insert_user( $userdata );

if ( is_wp_error( $user_id ) ) {
    $error_code = array_key_first( $user_id->errors );
    $error_message = $user_id->errors[$error_code][0];
    echo '<div class="error">' . $error_message . '</div>';
}

Retrieving a post and handling errors

Getting a post by its ID and checking if the result is an error.

$post_id = 42;
$post = get_post( $post_id );

if ( is_wp_error( $post ) ) {
    $error_message = $post->get_error_message();
    echo '<div class="error">' . $error_message . '</div>';
} else {
    echo '<h1>' . $post->post_title . '</h1>';
}

Adding a custom taxonomy term and handling errors

Adding a new custom taxonomy term and checking for errors.

$term = 'New Term';
$taxonomy = 'custom_taxonomy';

$result = wp_insert_term( $term, $taxonomy );

if ( is_wp_error( $result ) ) {
    $error_message = $result->get_error_message();
    echo '<div class="error">' . $error_message . '</div>';
} else {
    echo 'Term added successfully!';
}

Updating post meta data and handling errors

Updating a post’s metadata and checking for errors.

$post_id = 42;
$meta_key = 'custom_meta_key';
$new_meta_value = 'New Value';

$result = update_post_meta( $post_id, $meta_key, $new_meta_value );

if ( is_wp_error( $result ) ) {
    $error_message = $result->get_error_message();
    echo '<div class="error">' . $error_message . '</div>';
} else {
    echo 'Post meta updated successfully!';
}