函数文档

is_wp_error()

💡 云策文档标注

概述

is_wp_error() 是 WordPress 核心函数,用于检查给定变量是否为 WP_Error 类的实例。它常用于错误处理,确保在操作失败时能安全地处理错误对象。

关键要点

  • 函数接受一个参数 $thing(混合类型,必需),返回布尔值表示是否为 WP_Error 实例
  • 当参数是 WP_Error 实例时,会触发 is_wp_error_instance 动作钩子,传递错误对象
  • 广泛用于 WordPress 核心和扩展中,如插件安装、REST API、用户管理等场景的错误检测

代码示例

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

注意事项

  • 使用前需确保已包含相关文件,WP_Error 类通常在 WordPress 初始化时自动加载
  • 错误处理时建议结合 WP_Error 类的方法(如 get_error_message())获取详细信息
  • 注意版本兼容性,该函数自 WordPress 2.1.0 引入

📄 原文内容

Checks whether the given variable is a WordPress Error.

Description

Returns whether $thing is an instance of the WP_Error class.

Parameters

$thingmixedrequired
The variable to check.

Return

bool Whether the variable is an instance of WP_Error.

Source

function is_wp_error( $thing ) {
	$is_wp_error = ( $thing instanceof WP_Error );

	if ( $is_wp_error ) {
		/**
		 * Fires when `is_wp_error()` is called and its parameter is an instance of `WP_Error`.
		 *
		 * @since 5.6.0
		 *
		 * @param WP_Error $thing The error object passed to `is_wp_error()`.
		 */
		do_action( 'is_wp_error_instance', $thing );
	}

	return $is_wp_error;
}

Hooks

do_action( ‘is_wp_error_instance’, WP_Error $thing )

Fires when is_wp_error() is called and its parameter is an instance of WP_Error.

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    example with wp_insert_user

    $email = 'test@test.com';
    $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];
    }