Reading block content can become useful if you’re building blocks that will interact with other blocks or maybe a plugin that will enhance the whole experience of using the Block Editor.
As in the previous tutorial, where we talked about How to Programmatically add a block in the WordPress Block Editor, we will use the same approach here. You won’t need any compiling or anything to learn how to read the content from a block.
How to get access to Blocks?
To get access to blocks within the WordPress Block Editor, you’ll have to use the global variable
wp. Then, we’ll get into the store (data) of the block editor and that’s how we’ll read the data we need.
To be honest, there is nothing too special working with this. But when you don’t know where to look, it can feel magic.
I’d advise you, if you’re working a lot with blocks, to bookmark this link: https://developer.wordpress.org/block-editor/reference-guides/data/data-core-block-editor/. Here, you’ll be able to read the information about all methods that you can get when working with the data of the block editor.
Now, let’s see how to get all blocks:
wp.data.select( 'core/block-editor' ).getBlocks()
And then, you’ll get an array of objects for each block.
How to get the currently selected Block?
Let’s say that we want the information of the currently selected block, how to do that?
There is a method for that:
wp.data.select( 'core/block-editor' ).getSelectedBlock()
This will then return only 1 object. It will be the same object format as what we get when getting all blocks. Depending on the type of the object, it will have different attributes.
How to get the content of the previous Block?
To get the content from the previous block in the WordPress block editor, we’ll have to use the previous method with another one.
The previously mentioned method will get the information of the currently selected block.
Then, we’ll get the block
clientId parameter and use that to get the previous block.
const clientId = wp.data.select( 'core/block-editor' ).getSelectedBlock().clientId; const previousBlock = wp.data.select('core/block-editor').getAdjacentBlockClientId( clientId, -1 );
In the method
getAdjacentBlockClientId, we pass the
clientId of the currently selected block and we also pass
-1 to get the previous block. If you pass
-2, it will get the block before the previous block.
The same way can be done to get the information of the next block as well. But you pass positive numbers such as
Fetching Content from Previous Block & Put it in a textarea
This is something I did for my AI Blocks Plugin. I used the previous block content to fill the textarea. Once the user clicks the button, it will use that content to generate an AI image.