9

Back in TMCE days, we could easily get editor content with editor.getContent(). However in new Gutenberg editor, I can't find a method to do that.

I need all editor content as HTML (the way it will be saved in database).

I found wp.block.serialize() method which sounds promising. But seems to need blocks (as a parameter). So I'm kind of stuck.

shramee
  • 3,632
  • 19
  • 37

4 Answers4

10

As of version 3.1. of Gutenberg, try this:

to get the plain block content:

var originalContent = wp.data.select( "core/editor" ).getCurrentPost().content;
var editedContent = wp.data.select( "core/editor" ).getEditedPostContent();

to render the post (transform to blocks):

wp.blocks.parse( editedContent );
Flow
  • 315
  • 3
  • 7
4

You may want to explore the window._wpGutenbergPost.content which has both a raw and rendered content. This is, at the moment. Things will probably change :)

  • Thanks Andrea, but that seems to return content saved in the database, not what user has edited in the editor... – shramee Jan 11 '18 at 13:11
  • This seems to be outdated. See my answer [below](https://stackoverflow.com/a/51023185/2703039). – Flow Jun 25 '18 at 12:10
3

You may use selectors it allows us to retrieve data and similarly, For example, to update the title of the post being edited in Gutenberg, you can do:

wp.data.dispatch( 'core/editor' ).editPost( { title: 'New Title' } );

You can check the actions file here https://github.com/WordPress/gutenberg/blob/v2.9.2/editor/store/actions.js , to see the full list of the actions defined by the core/editor namespace.

See more: https://riad.blog/2018/06/07/efficient-client-data-management-for-wordpress-plugins/

Adel
  • 3,436
  • 2
  • 16
  • 27
  • How to edit the content? I tried wp.data.dispatch( 'core/editor' ).editPost( { content: '\n

    I love you daddy dddhhhhh.

    \n' } ); but it updates the code in the HTML editor and blocks does not update its content
    – Atef Sep 08 '18 at 22:55
0

I have a similar issue but unable to comment. The answer Flow provided which does set the post title but as of 4.5.1 does not handle the content.

In order to update the post content I was able to insert a paragraph block. Here is my code:

wp.data.dispatch( 'core/editor' ).editPost( { title: 'New Title' } );
var editedContent = wp.data.select( "core/editor" ).getEditedPostContent();
var newBlock = wp.blocks.createBlock( "core/paragraph", {
    content: editedContent,
});
wp.data.dispatch( "core/editor" ).insertBlocks( newBlock );
ant-C
  • 35
  • 5