WP_REST_Controller::add_additional_fields_to_object() WordPress Method

The WP_REST_Controller::add_additional_fields_to_object() Wordpress method allows for the addition of additional fields to a JSON object that is being returned by the REST API. This is helpful if you need to add extra data to an API response that is not already being returned.

WP_REST_Controller::add_additional_fields_to_object( array $prepared, WP_REST_Request $request ) #

Adds the values from additional fields to a data object.


Parameters

$prepared

(array)(Required)Prepared response array.

$request

(WP_REST_Request)(Required)Full details about the request.


Top ↑

Return

(array) Modified data object with additional fields.


Top ↑

Source

File: wp-includes/rest-api/endpoints/class-wp-rest-controller.php

	protected function add_additional_fields_to_object( $prepared, $request ) {

		$additional_fields = $this->get_additional_fields();

		$requested_fields = $this->get_fields_for_response( $request );

		foreach ( $additional_fields as $field_name => $field_options ) {
			if ( ! $field_options['get_callback'] ) {
				continue;
			}

			if ( ! rest_is_field_included( $field_name, $requested_fields ) ) {
				continue;
			}

			$prepared[ $field_name ] = call_user_func( $field_options['get_callback'], $prepared, $field_name, $request, $this->get_object_type() );
		}

		return $prepared;
	}


Top ↑

Changelog

Changelog
VersionDescription
4.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.