5
votes

I have several robots, written in Node.js, to auto-generate HTML contents and put them into several Wordpress sites using REST API. Recently Wordpress 5.0 has been officially released, and Gutenberg has become the default editor. All the old posts, as well as those generated by robots, will be encapsulated in a single "Classic" block.

As most of us already know, additional markup should be added to convert the HTML elements into blocks, and there has been a "Convert to Blocks" button to convert them into blocks in Gutenberg UI. Is there any convenient way (say making use of built-in functions) to do the same things as "Convert to Blocks" programmatically, or we should wrap those Gutenberg related markups one by one? Any help should be appreciated

1

1 Answers

4
votes

May be this is a little late, but if someone is still looking for a solution here's how you do it.

This code assumes that your classic block is the first one:

var block = wp.data
      .select("core/editor")
      .getBlocks()[0];

wp.data.dispatch( 'core/editor' ).replaceBlocks(block.clientId, wp.blocks.rawHandler( 
  { HTML: wp.blocks.getBlockContent( block ) }
));

If you want to do it for all classic blocks, simply iterate overall blocks and look for block name core/freeform to convert it like this:

wp.data.select("core/editor").getBlocks().forEach(function(block, blockIndex){
  if (block.name === "core/freeform"){
    wp.data.dispatch( 'core/editor' ).replaceBlocks(block.clientId, wp.blocks.rawHandler( 
      { HTML: wp.blocks.getBlockContent( block ) }
    ));    
  }
})