I’m currently testing the new Gutenberg plugin with my own developed theme and plugin. My theme has a custom meta box with an action for the user. Once the user click this action the post content is completely deleted and a new ‘custom’ content is added to the default tinyMce editor.

Example: tinymce.get(“content”).setContent(“my custom content”);

This of course does not work anymore with the new Guteberg Editor and I’m struggeling to find a solution.

So Basically what I’m trying to do is to remove all block/content from the gutenberg editor and add a new block (text) with my custom content via javascript. Does anyone have any hint to point me in the right direction?

up vote 3 down vote accepted

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 );

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.