Using WordPress ‘block_editor_rest_api_preload()’ PHP function

The block_editor_rest_api_preload() WordPress PHP function preloads common data used with the block editor. This is achieved by specifying an array of REST API paths that will be preloaded for a given block editor context.

Usage

Let’s say we want to preload some REST API paths for our custom block editor context. Here’s how to use the function:

block_editor_rest_api_preload(array('/wp/v2/posts?per_page=10', '/wp/v2/pages?per_page=10'), $block_editor_context);

In this case, the latest 10 posts and 10 pages will be preloaded for the given block editor context.

Parameters

  • $preload_paths (array of strings) – This is a required parameter, which is a list of paths to preload.
  • $block_editor_context (WP_Block_Editor_Context) – This is a required parameter. It represents the current block editor context.

More information

See WordPress Developer Resources: block_editor_rest_api_preload()

This function is particularly useful when you need to enhance the performance of the block editor by preloading required data.

Examples

Preloading Posts and Pages

$preload_paths = array('/wp/v2/posts?per_page=5', '/wp/v2/pages?per_page=5');
block_editor_rest_api_preload($preload_paths, $block_editor_context);

This code will preload the latest 5 posts and 5 pages for the block editor context.

Preloading Specific Post and Page

$preload_paths = array('/wp/v2/posts/1', '/wp/v2/pages/2');
block_editor_rest_api_preload($preload_paths, $block_editor_context);

This code will preload the post with ID 1 and the page with ID 2.

Preloading Posts with Specific Status

$preload_paths = array('/wp/v2/posts?status=publish');
block_editor_rest_api_preload($preload_paths, $block_editor_context);

This code will preload all posts with ‘publish’ status.

Preloading Posts from Specific Category

$preload_paths = array('/wp/v2/posts?categories=10');
block_editor_rest_api_preload($preload_paths, $block_editor_context);

This code will preload all posts from the category with ID 10.

Preloading Users

$preload_paths = array('/wp/v2/users?per_page=5');
block_editor_rest_api_preload($preload_paths, $block_editor_context);

This code will preload the latest 5 users for the block editor context.