函数文档

wp_send_json_error()

💡 云策文档标注

概述

wp_send_json_error() 是一个 WordPress 函数,用于向 Ajax 请求发送 JSON 格式的错误响应。它确保响应中包含 success 键,其值为 false,并可处理 WP_Error 对象以输出详细的错误信息。

关键要点

  • 函数用于发送 Ajax 请求的 JSON 错误响应,自动设置 success 为 false。
  • 参数 $value 可选,若为 WP_Error 对象,则自动处理为包含错误代码和消息的数组;其他类型直接输出。
  • 参数 $status_code 和 $flags 可选,分别用于设置 HTTP 状态码和 json_encode() 选项。
  • 函数内部调用 wp_send_json() 来发送响应,并终止脚本执行。

代码示例

$error = new WP_Error( '001', 'No user information was retrieved.', 'Some information' );
wp_send_json_error( $error );

注意事项

  • 仅调用 wp_send_json_error() 而不带参数可能返回 HTTP 200 状态码,建议设置 $status_code 如 500 以触发错误处理。
  • 函数从 WordPress 3.5.0 版本引入,后续版本增加了参数处理功能。

📄 原文内容

Sends a JSON response back to an Ajax request, indicating failure.

Description

If the $value parameter is a WP_Error object, the errors within the object are processed and output as an array of error codes and corresponding messages. All other types are output without further processing.

Parameters

$valuemixedoptional
Data to encode as JSON, then print and die.

Default:null

$status_codeintoptional
The HTTP status code to output.

Default:null

$flagsintoptional
Options to be passed to json_encode(). Default 0.

More Information

The response object will always have a success key with the value false. If anything is passed to the function in the $data parameter, it will be encoded as the value for a data key.

Source

function wp_send_json_error( $value = null, $status_code = null, $flags = 0 ) {
	$response = array( 'success' => false );

	if ( isset( $value ) ) {
		if ( is_wp_error( $value ) ) {
			$result = array();
			foreach ( $value->errors as $code => $messages ) {
				foreach ( $messages as $message ) {
					$result[] = array(
						'code'    => $code,
						'message' => $message,
					);
				}
			}

			$response['data'] = $result;
		} else {
			$response['data'] = $value;
		}
	}

	wp_send_json( $response, $status_code, $flags );
}

Changelog

Version Description
5.6.0 The $flags parameter was added.
4.7.0 The $status_code parameter was added.
4.1.0 The $value parameter is now processed if a WP_Error object is passed in.
3.5.0 Introduced.

User Contributed Notes