• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

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

Wordpress · October 21, 2022

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'));
  }
} );

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • The Quad Cortex Desktop Editor is Finally Announced
  • Thoughts on the Flipper Zero
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • How To Install Eufy Security Cameras Without Drilling or Using Screws
  • Smoke Detector Randomly Goes Off Early Hours of The Morning

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz