Parsing a raw WordPress post with blocks
Gutenberg blocks are great. I love the authoring experience using WordPress with blocks.
The trick was figuring out how to use that authoring experience in a headless context with a Next.js site. We somehow need to get the blocks and translate them into a React context.
Raw WordPress post
The first step is to make sure you can grab the raw post content from the REST API which will require authorization. Posts are usually publicly available with the WordPress API, however when you add the query parameter _context=edit
, you will need authorization. See my article Setup OAuth with WordPress.com to use as headless CMS for info.
Once you're able to make a request with the _content=edit query parameter, you will get another property on the content property - raw. The raw data is the custom WordPress blocks markup that uses HTML comments to store additional data for each block. It will look something like:
It's not super hard to understand. Just some HTML wrapped in custom comment tags that mean something to Gutenberg. It's not super important to understand this as we're going to parse it into a JSON object that will be easier to work with.
Parse post into JSON blocks object
Now that we made our fetch request and have the raw post content, we now need to install the block parser:
Now we can use the parser like this:
That will parse the comment style block post into an array of individual JSON block objects.
I haven't quite figured out why they create a number of blocks with the blockname of null
, but I have so far just filtered those out.
Now we have our blocks in JavaScript which opens up a whole huge range of possibilities.
Next we'll deal with how to turn those block objects into React components.