How to get Gutenberg blocks data in WordPress with JavaScript
In this article I’m going to explain how to get Gutenberg blocks data in WordPress with JavaScript.
To get the Gutenberg blocks data you can use one of a few approaches, depending on your needs.
Get all registered blocks
One way is to use the Blocks package. A WordPress is using multiple JavaScript packages in order to handle specific functionality.
The Block package which contains methods to manage Gutenberg blocks is available under the wp.blocks
global object.
window.wp.blocks
Result:
To get the data of all of the available Gutenberg blocks you’ll have to use the getBlockTypes()
method. It returns the array of objects, and it is available in the global scope inside the Gutenberg editor.
window.wp.blocks.getBlockTypes()
Result:
💡 NOTE: While the Blocks module is available as a global property inside the Gutenberg editor, you can install it independently via npm
for your project.
Get blocks added to the post
You can also get the data of the blocks that are added to the post. For this appoach we’ll be using the Data module, which is available in the Data package.
The Data module is used to manage the state of the Gutenberg editor and it is available via global wp.data
property.
window.wp.data
Result:
The way to get the added elements data is to use the select
method of the Data module with a core/block-editor
namespace as the argument.
This will return the object of the store’s selectors.
window.wp.data.select('core/block-editor')
Result:
Finally you can use the desired method to get the data, in our case the getBlocks()
method.
window.wp.data.select('core/block-editor').getBlocks()
Result:
💡 NOTE: If you don't have any elements added to the post, the getBlocks()
method will return an empty array.