How to get Gutenberg blocks data in WordPress with JavaScript

Published: · Reading time: 2 min

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.

  1. Get all registered blocks
  2. Get blocks added to the post

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:

WordPress Blocks module object
WordPress Blocks module object

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:

Blocks module getBlockTypes() method
Blocks module's getBlockTypes() method

💡 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:

WordPress Data module object
WordPress Data module object

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:

WordPress core/block-editor object
WordPress core/block-editor object

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:

WordPress getBlocks() object
WordPress getBlocks() object

💡 NOTE: If you don't have any elements added to the post, the getBlocks() method will return an empty array.

Like this article? Share it on: