10

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?

1

1 Answer 1

16

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/block-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/block-editor' ).insertBlocks( block );

On further inspection, there's a simpler method:

let block = wp.blocks.createBlock( 'core/paragraph', { content: 'test' } );
wp.data.dispatch( 'core/block-editor' ).insertBlocks( block );
2
  • The solution is deprecated. Use 'core/block-editor'...
    – user227828
    Nov 25, 2022 at 13:49
  • Hence the bolded note that the API was not final, I've edited the question to use block-editor though, and the code still worked but told users what to change
    – Tom J Nowell
    Nov 26, 2022 at 23:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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