The beauty of Gutenberg is that the HTML content is more structured and semantic while also simplifying the user experience. All of the data is stored in the post content, which is also great because we don’t have to request a bunch of post meta to render the page. On the other hand, if nothing is stored in post meta, how do you fetch this structured block data via the WordPress REST API?
All you need to do to parse Gutenberg generated content into block data in PHP is use the
gutenberg_parse_blocks() function. Just pass your content to that function and you will get back a JSON data structure representing the Gutenberg blocks on your page.
So how do we surface all that block data in the WordPress REST API?
This will hook into the
rest_api_init action and add our closure as a callback. We start by getting all post types that support the editor. Then, for each post type, we call
gutenberg_can_edit_post_type()to check if our post type actually supports Gutenberg. If it does, we use the
register_rest_field() function to add a
blocksproperty to the object returned by the WordPress REST API. The
get_callback bit is all we really need to declare since we are only concerned with outputting the blocks in the API. That get callback need only return a call to
gutenberg_parse_blocks() after passing in the raw post content for the requested post.