rest_validate_null_value_from_schema()
云策文档标注
概述
rest_validate_null_value_from_schema() 是一个 WordPress REST API 函数,用于根据模式验证值是否为 null。如果值不是 null,则返回 WP_Error 错误对象。
关键要点
- 函数用于验证参数值是否为 null,基于 REST API 模式。
- 接受两个参数:$value(要验证的值)和 $param(参数名,用于错误消息)。
- 返回值:如果值为 null 则返回 true,否则返回 WP_Error 对象,包含错误代码 'rest_invalid_type' 和描述性消息。
- 该函数在 WordPress 5.7.0 版本中引入。
代码示例
function rest_validate_null_value_from_schema( $value, $param ) {
if ( null !== $value ) {
return new WP_Error(
'rest_invalid_type',
/* translators: 1: Parameter, 2: Type name. */
sprintf( __( '%1$s is not of type %2$s.' ), $param, 'null' ),
array( 'param' => $param )
);
}
return true;
}注意事项
- 函数内部使用 WP_Error 类来返回错误,确保错误处理与 WordPress 标准一致。
- 错误消息支持国际化,使用 __() 函数进行翻译。
- 该函数被 rest_validate_value_from_schema() 调用,用于更广泛的模式验证。
原文内容
Validates a null value based on a schema.
Parameters
$valuemixedrequired-
The value to validate.
$paramstringrequired-
The parameter name, used in error messages.
Source
function rest_validate_null_value_from_schema( $value, $param ) {
if ( null !== $value ) {
return new WP_Error(
'rest_invalid_type',
/* translators: 1: Parameter, 2: Type name. */
sprintf( __( '%1$s is not of type %2$s.' ), $param, 'null' ),
array( 'param' => $param )
);
}
return true;
}
Changelog
| Version | Description |
|---|---|
| 5.7.0 | Introduced. |