Custom Classes
Rest API

Working with the WordPress REST API

The entirety of the Block Editor works with the WordPress REST API (opens in a new tab) along with the EntityProvider API to read and write data to the database. Gutenberg provies us with quite a few helper functions and hooks to allow us to easily work with the data. Some of those are noted below along with a few examples.

Core Data

Most of the data reading/writing is done with functions from the core/data (opens in a new tab) package. Most specifically:

The examples use useSelect or useDispatch which is discussed in the hooks documentation.

Single Post

Fetch a single post by id (123) and only return the id, title, and featured_media id from the REST.

import { useSelect } from '@wordpress/data';
 
/**
 * Fetch a single post.
 *
 * @dep {int} selected post id of a selected value.
 */
const selectedPost = useSelect(
	( select ) => select( 'core' ).getEntityRecord(
			'postType',
			'post',
			123,
			{ _fields: 'id,title,featured_media' }
		) || {},
	[ selected ]
);

Multipe Posts

The example below gets all posts for a custom post type and returns only the id and title fields.

import { useSelect } from '@wordpress/data';
 
/**
 * Fetch all posts.
 */
const allPosts = useSelect(
	( select ) => select( 'core' ).getEntityRecords(
		'postType',
		'post',
		{ per_page: -1, _fields: 'id,title' }
	) || [],
);

Edit Current Post

The example below updates the category for the current post. The editPost function assumes the current post.

import { useDispatch } from '@wordpress/data';
 
/**
 * Dispatcher
 */
const { editPost } = useDispatch( 'core/editor' );
 
/**
 * Can be used in a callback or useEffect hook.
 */
editPost({ category: [ 10 ] });

Edit Entity

The example below updates the category for a specific post by id.

import { useDispatch } from '@wordpress/data';
 
/**
 * Dispatcher
 */
const { editEntityRecord } = useDispatch( 'core' );
 
/**
 * Function to update category for the post id given.
 */
editEntityRecord( 'postType', 'post', 123, { category: [ 10 ] } );

Meta

Meta can be read from and written to using a single method that is not documented in the Block Editor Handbook, useEntityProp.

It expects a data type, a value, and the part of the entity we're returning. In the example below, postType, the current post type slug, and meta which will return the meta object for the current post slug.

The returned value is an array containing the meta object and a setter which expects an updated meta object.

Example: Setup

import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
 
...
 
/**
 * Get the post type to pass to the entity provider.
 *
 * @see https://github.com/WordPress/gutenberg/blob/8d46fcdfdb929739b10ffe715073d15db5123ff9/packages/core-data/src/entity-provider.js#L91
 */
const postType = useSelect(
	( select ) => select( 'core/editor' ).getCurrentPostType(),
	[]
);
 
/**
 * We're needing to fetch meta prior to our post object.
 * request so we can leverage meta change to trigger a useSelect update.
 */
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
 
...
 
/**
 * Callback to be used to update meta values.
 */
setMeta({ ...meta, meta_key_registered: nextValue });

apiFetch

In addition to these functions (and others) we can make direct API fetch requests using the apiFetch (opens in a new tab) function which provides a bunch of middlewares to help with authentication and working with WordPress data specifically.

Example

import apiFetch from '@wordpress/api-fetch';
 
...
 
/**
 * Make fetch for via config.
 */
const fetchConfig = () => {
	( async () => {
		let response = 0;
 
		try {
			response = await apiFetch( {
				path: `/wp/v2/posts/${ postId }`,
			} );
			// Do something with response here.
		} catch ( error ) {
			response = 0;
			// Set some error here.
		} finally {
			// Stop loading.
		}
	} )();
};
 
fetchConfig();

CAP Authors

Endpoint for the pmc/contributors block which returns CAP objects from CAP slugs.

  • Extends: Endpoint

_get_route

Return endpoint's route, including any URL parameters (dynamic parts).

_get_args

Return endpoint's arguments to be passed to register_rest_route().

callback

Build list of taxonomies that can be used as curation sources for the Carousel block.

  • $data: WP_REST_Request — Additional data attached to the API request.

Modifications

Apply Gutenberg-specific modifications to WP's REST API.

hook_post_responses

Hook into all post types' REST responses.

add_truncated_content

Add truncated content to REST responses, with HTML tags preserved.

  • $response: WP_REST_Response — REST response object.
  • $post: WP_Post — Post object.
  • $request: WP_REST_Request — REST request object.

add_dd_toc_to_rest_response

Add Digital Daily's Table of Contents data to REST response for use in the Fullscreen Cover block.

  • $response: WP_REST_Response — REST response object.
  • $post: WP_Post — Post object.
  • $request: WP_REST_Request — REST request object.

register_custom_rest_field

Adds a new field to a post type's REST response.

get_pmc_list_relation

For a given PMC list, return the relation to the PMC.

  • $post: array — post object.

get_pmc_vertical_category

For a given vertical term, return the related FM category field ids.

  • $term: array — REST object for term.

filter_legacy_meta_json

Filters REST json to add legacy meta handlers.

  • $response: \WP_REST_Response — rest response.
  • $server: \WP_REST_Server — rest server.
  • $request: \WP_REST_Request — rest request.

modify_global_search_query

Apply custom query args to the global search endpoint.

  • $query_args: array — query args.
  • $request: \WP_REST_Request — wp rest request.

filter_global_search_json

Apply fields to global search endpoint.

  • $response: \WP_REST_Response — rest response.
  • $server: \WP_REST_Server — rest server.
  • $request: \WP_REST_Request — rest request.

Post Search

Endpoint to get post by URL.

  • Extends: Endpoint

_get_route

Return endpoint's route, including any URL parameters (dynamic parts).

_get_args

Return endpoint's arguments to be passed to register_rest_route().

callback

Get post data by URL.

  • $request: WP_REST_Request — Additional data attached to the API request.

Namespace Slug

Set consistent namespace slug without repetition.