函数文档

rest_is_field_included()

💡 云策文档标注

概述

rest_is_field_included() 函数用于在 WordPress REST API 中判断指定字段是否应包含在响应体中,支持处理嵌套字段(如 parent.child)。该函数通过检查字段数组,根据父子关系逻辑返回布尔值。

关键要点

  • 函数接受两个参数:$field(要测试的字段字符串)和 $fields(端点支持的字段数组)。
  • 返回布尔值,指示是否包含该字段。
  • 如果父字段被传入,任何嵌套子字段的存在都会使函数返回 true(例如,"title" 在 "title.raw" 或 "title.rendered" 存在时返回 true)。
  • 函数逻辑包括直接匹配和基于字符串前缀的父子关系检查。

代码示例

function rest_is_field_included( $field, $fields ) {
    if ( in_array( $field, $fields, true ) ) {
        return true;
    }

    foreach ( $fields as $accepted_field ) {
        /*
         * Check to see if $field is the parent of any item in $fields.
         * A field "parent" should be accepted if "parent.child" is accepted.
         */
        if ( str_starts_with( $accepted_field, "$field." ) ) {
            return true;
        }
        /*
         * Conversely, if "parent" is accepted, all "parent.child" fields
         * should also be accepted.
         */
        if ( str_starts_with( $field, "$accepted_field." ) ) {
            return true;
        }
    }

    return false;
}

注意事项

  • 该函数自 WordPress 5.3.0 版本引入。
  • 广泛用于多个 REST API 控制器的 prepare_item_for_response() 方法中,以优化响应字段选择。
  • 确保字段名和嵌套结构符合 API 端点定义,避免逻辑错误。

📄 原文内容

Given an array of fields to include in a response, some of which may be nested.fields, determine whether the provided field should be included in the response body.

Description

If a parent field is passed in, the presence of any nested field within that parent will cause the method to return true. For example “title” will return true if any of title, title.raw or title.rendered is provided.

Parameters

$fieldstringrequired
A field to test for inclusion in the response body.
$fieldsarrayrequired
An array of string fields supported by the endpoint.

Return

bool Whether to include the field or not.

Source

function rest_is_field_included( $field, $fields ) {
	if ( in_array( $field, $fields, true ) ) {
		return true;
	}

	foreach ( $fields as $accepted_field ) {
		/*
		 * Check to see if $field is the parent of any item in $fields.
		 * A field "parent" should be accepted if "parent.child" is accepted.
		 */
		if ( str_starts_with( $accepted_field, "$field." ) ) {
			return true;
		}
		/*
		 * Conversely, if "parent" is accepted, all "parent.child" fields
		 * should also be accepted.
		 */
		if ( str_starts_with( $field, "$accepted_field." ) ) {
			return true;
		}
	}

	return false;
}

Changelog

Version Description
5.3.0 Introduced.