1. 8
    Expose Gutenberg Blocks to the REST API with the wp-rest-blocks Plugin
    2m 51s

Expose Gutenberg Blocks to the REST API with the wp-rest-blocks Plugin

Share this video with your friends

Send Tweet

We will expose the Gutenberg blocks to the REST API. Rather than having a single content blob, we now have the content split into blocks on the API. We can get accompanying data from each block and have more control when we render on the frontend.

This will be done by installing the wp-rest-blocks plugin. The catch here is that it isn't available in the WordPress plugin directory. We will need to download a zip from the wp-rest-blocks GitHub to then upload and activate in WordPress.

Kevin Cunningham
Kevin Cunningham(instructor)
~ 2 years ago

There are two points where this plugin install becomes challenging in later versions of WordPress.

In version 0.5.0 of the plugin and 6.0.1 of WordPress, I've had to do two more steps.

  • I've used Local to open a Site Shell and in there gone to the plugin's directory. Within the directory, I've ran composer install which installs dependencies that used to be shipped with the code.
  • I've had to edit the code in src/posts.php. When I installed the plugin, the blocks no longer rendered in the editor. By changing what the new REST API field is called, from blocks to blocksData, the editor rendered the blocks correctly and the data is available on the API. The updated code looks like this:
	register_rest_field(
		$types,
		'blocksData',
		[
			'get_callback'    => __NAMESPACE__ . '\\blocks_get_callback',
			'update_callback' => null,
			'schema'          => [
				'description' => __( 'Blocks.', 'wp-rest-blocks' ),
				'type'        => 'object',
				'context'     => [ 'embed', 'view', 'edit' ],
				'readonly'    => true,
			],
		]
	);

The creator and maintainer of this plugin is a core WP maintainer and I've reached out to them to see if there is a less "hacky" fix. I'll hold off until I hear from them and will upload a supplementary or updated video to cover this.