Programmatically Clicking the “Convert to Blocks” Button in WordPress Gutenberg on the Edit Screen

In the beginning, I was one of the loud developers protesting WordPress Gutenberg. But, now that Gutenberg has been around for a while, I’ve grown to like it. I can’t tell if it’s because of Stockholm syndrome or if it has actually improved.

Anyway.

One of the looming problems users of WordPress will still face is the fact if you programmatically insert content into WordPress using wp_insert_post or however else you insert content (say from a CSV or API) you’ll find that WordPress will put it into a Classic Editor block. You will then be prompted to “Convert to blocks” in the editor.

Now, clicking this button isn’t difficult. You focus on the content and click it. But, I needed a way to automate this when the WordPress post edit screen loads. It turns out it’s a little more involved than firing a click event on the convert to blocks button.

(function () {
    const block = wp.data.select('core/block-editor' ).getBlocks()[0];

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

The code assumes the first block in our editor is a classic block (which is the case for non-converted Gutenberg posts). We get the block using the WordPress JS API. If the block exists we can call the replaceBlocks method and pass in the block ID, then replace it using the rawHandler method to generate our blocks.

Throw this code into a Javascript file and use admin_enqueue_scripts to load it on your edit screen. Here is how I do it inside of my functions.php file.

add\_action( 'admin\_enqueue\_scripts', function() {
  global $pagenow;

  if( 'post.php' == $pagenow ) {
    wp\_enqueue\_script('block-convert-js', get\_stylesheet\_directory\_uri() . '/convert-to-blocks.js', array(), filemtime( get\_stylesheet\_directory() . '/convert-to-blocks.js'));
  }
} );