6

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

kychung
  • 73
  • 6

1 Answers1

4

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 ) }
    ));    
  }
})
Akshay Raje
  • 852
  • 9
  • 20
  • Is there an npm package I can use to access `wp` presumably I would import this from an npm package right? – Max Carroll Jul 13 '20 at 17:50
  • @MaxCarroll There are several WordPress packages (https://github.com/WordPress/gutenberg/tree/master/packages) that use the wp global but depending on how you do it, you may not need them. that code appears to use the 'wp-blocks', 'wp-editor' packages which is compiled into the standard wordpress install. https://developer.wordpress.org/block-editor/packages/ – Will Dec 04 '20 at 19:16
  • This sounds like it should be exactly what I want, but I can't quite get it to work (even after updating 'core/editor' to be 'core/block-editor'). getBlocks always returns an empty array for me, regardless of how many blocks are present in the current post. Not sure what I'm doing wrong. Calling getBlocks too early? I've also tried wrapping it in wp.domReady( function() { }; – MadtownLems May 26 '21 at 19:33