Skip to content

REST API

Radoslav Georgiev edited this page Oct 21, 2018 · 2 revisions

Overview

Starting with Ultimate Fields 2, the plugin can automatically add data to the WordPress REST API.

Ultimate Fields can associate various locations with endpoints in the API. For the built-in content types (all except Options), the fields are added to the normal endpoints in WordPress. For the options page, there is a separate endpoint, which exposes all registered options.

Location Endpoint(s) Created by Ultimate Fields
Attachment wp-json/wp/v2/media No
Comment wp-json/wp/v2/comments No
Post_Type Same as WP Post Types (ex. wp-json/wp/v2/posts) No
Taxonomy Same as WP Taxonomies (ex. wp-json/wp/v2/categories) No
User wp-json/wp/v2/users No
Options /wp-json/ultimate-fields/v2/options/ Yes

Usage in the UI

When you are using the administration interface, the supported locations will have a REST API tab.

rest-api-settings

The tab contains a couple of fields:

  1. Expose allows you to associate the container with the REST API.
  2. When exposed, there will be a second field called API FIelds. This is a repeater, which lets you choose which fields to expose and whether you would like them to be read-only or not.

Writeable fields will follow the same access logic as WordPress' built-in fields. If a user can edit them, they will be also able to edit the custom fields, which you created.

For Options Pages, the user must be logged in and have the same capability as the options page, which containers are added to.

Usage in PHP

Adding fields to the rest API is done through the expose_in_rest and api_fields arguments in the $args array or the expose_api_fields method of a location.

The api_fields argument and the expose_api_fields method accept an array of fields. The array can contain either simply the name of the field or a pair of the name of the field and the access type:

$location->expose_api_fields(array(
	'event_start',
	'event_end' => WP_REST_Server::EDITABLE
));

If you include just the field name, it will be added as a read-only field. To make a field editable, you need to use the WP_REST_Server::EDITABLE constant as the value.

If you are using the ->add_location method, you can do it this way:

$container->add_location( 'post_type', 'event', array(
	'expose_in_rest' => true,
	'api_fields' => array(
		'event_start',
		'event_end' => WP_REST_Server::EDITABLE
	)
));
Clone this wiki locally