Firing Wordpress Gutenberg "Convert to Blocks" programmatically
Asked Answered
D

1

7

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

Disembarrass answered 8/12, 2018 at 4:21 Comment(0)
C
6

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 ) }
    ));    
  }
})
Cantara answered 23/2, 2019 at 10:59 Comment(3)
Is there an npm package I can use to access wp presumably I would import this from an npm package right?Prince
@MaxCarroll There are several WordPress packages (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. developer.wordpress.org/block-editor/packagesDiaconal
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() { };Tetrasyllable

© 2022 - 2024 — McMap. All rights reserved.