钩子文档

rest_pre_get_setting

💡 云策文档标注

概述

rest_pre_get_setting 是一个 WordPress REST API 过滤器,用于在获取设置值时进行干预。通过返回非空值,开发者可以覆盖默认的 get_option() 行为,自定义设置值的返回结果。

关键要点

  • 过滤器名称:rest_pre_get_setting
  • 主要用途:允许在 REST API 中劫持设置值,覆盖内置行为
  • 参数:$result(设置值,可为标量或 null)、$name(设置名称)、$args(register_setting() 的参数数组)
  • 返回值:返回非空值将作为设置值替代默认值
  • 相关函数:与 WP_REST_Settings_Controller::get_item() 关联,用于检索设置
  • 版本历史:自 WordPress 4.7.0 引入

注意事项

使用此过滤器时,需确保返回的值与注册设置时的 schema 类型匹配(如 'string'、'boolean' 等),以避免数据不一致问题。


📄 原文内容

Filters the value of a setting recognized by the REST API.

Description

Allow hijacking the setting value and overriding the built-in behavior by returning a non-null value. The returned value will be presented as the setting value instead.

Parameters

$resultmixed
Value to use for the requested setting. Can be a scalar matching the registered schema for the setting, or null to follow the default get_option() behavior.
$namestring
Setting name (as shown in REST API responses).
$argsarray
Arguments passed to register_setting() for this setting.

More Arguments from register_setting( … $args )

Data used to describe the setting when registered.

  • type string
    The type of data associated with this setting.
    Valid values are 'string', 'boolean', 'integer', 'number', 'array', and 'object'.
  • label string
    A label of the data attached to this setting.
  • description string
    A description of the data attached to this setting.
  • sanitize_callback callable
    A callback function that sanitizes the option’s value.
  • show_in_rest bool|array
    Whether data associated with this setting should be included in the REST API.
    When registering complex settings, this argument may optionally be an array with a 'schema' key.
  • default mixed
    Default value when calling get_option().

Source

$response[ $name ] = apply_filters( 'rest_pre_get_setting', null, $name, $args );

Changelog

Version Description
4.7.0 Introduced.