Gutenberg – remove / add blocks with custom script

There’s probably a simpler way to do this, and if there isn’t you should open an issue on the Gutenberg GH issue tracker ( the API is not set in stone ).

Because the API is not set in stone, this answer may be useless when it’s finally done and merged. The first and best place to ask GB questions is on GitHub

You can eliminate all blocks using this:

wp.data.dispatch( 'core/editor' ).resetBlocks([]);

You can then create a new block programmatically:

let block = wp.blocks.createBlock( 'core/paragraph' );

Add text to it:

block.attributes.content.push( 'hello world' );

And insert it like this:

wp.data.dispatch( 'core/editor' ).insertBlocks( block );

On further inspection, there’s a simpler method:

let block = wp.blocks.createBlock( 'core/paragraph', { content: 'test' } );
wp.data.dispatch( 'core/editor' ).insertBlocks( block );

Leave a Comment