函数文档

_json_wp_die_handler()

💡 云策文档标注

概述

_json_wp_die_handler() 是 WordPress 中处理 JSON 请求时 wp_die() 的处理器函数,用于终止执行并返回 JSON 格式的错误响应。

关键要点

  • 函数作用:在 JSON 请求中,通过 wp_die() 调用此处理器,输出 JSON 错误数据并可选地终止脚本执行。
  • 参数说明:接受 $message(必需错误消息)、$title(可选错误标题)和 $args(可选控制行为的数组参数)。
  • 输出格式:构建包含 code、message、data(含 status 和可能的 error_data)及 additional_errors 的 JSON 数组。
  • HTTP 头设置:自动设置 Content-Type 为 application/json,可配置状态码和缓存控制头。
  • 相关函数:依赖 _wp_die_process_input() 处理输入,使用 status_header()、nocache_headers() 和 wp_json_encode() 辅助功能。

代码示例

function _json_wp_die_handler( $message, $title = '', $args = array() ) {
	list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );

	$data = array(
		'code'              => $parsed_args['code'],
		'message'           => $message,
		'data'              => array(
			'status' => $parsed_args['response'],
		),
		'additional_errors' => $parsed_args['additional_errors'],
	);

	if ( isset( $parsed_args['error_data'] ) ) {
		$data['data']['error'] = $parsed_args['error_data'];
	}

	if ( ! headers_sent() ) {
		header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
		if ( null !== $parsed_args['response'] ) {
			status_header( $parsed_args['response'] );
		}
		nocache_headers();
	}

	echo wp_json_encode( $data );
	if ( $parsed_args['exit'] ) {
		die();
	}
}

注意事项

  • 此函数主要用于内部处理,开发者通常通过 wp_die() 间接调用,而非直接使用。
  • 在 WordPress 5.1.0 版本中引入,确保兼容性时需注意版本要求。
  • 参数 $args 可覆盖默认行为,如设置 response 状态码或 exit 标志。

📄 原文内容

Kills WordPress execution and displays JSON response with an error message.

Description

This is the handler for wp_die() when processing JSON requests.

Parameters

$messagestringrequired
Error message.
$titlestringoptional
Error title. Default empty string.
$argsstring|arrayoptional
Arguments to control behavior.

Default:array()

Source

function _json_wp_die_handler( $message, $title = '', $args = array() ) {
	list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );

	$data = array(
		'code'              => $parsed_args['code'],
		'message'           => $message,
		'data'              => array(
			'status' => $parsed_args['response'],
		),
		'additional_errors' => $parsed_args['additional_errors'],
	);

	if ( isset( $parsed_args['error_data'] ) ) {
		$data['data']['error'] = $parsed_args['error_data'];
	}

	if ( ! headers_sent() ) {
		header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
		if ( null !== $parsed_args['response'] ) {
			status_header( $parsed_args['response'] );
		}
		nocache_headers();
	}

	echo wp_json_encode( $data );
	if ( $parsed_args['exit'] ) {
		die();
	}
}

Changelog

Version Description
5.1.0 Introduced.