A purple and white flower growing in front of a fence.

How To Insert Blocks In WordPress Block Editor

If you want to add a block to the WordPress block editor, you can use the data and blocks packages, like this:

//Create a paragrah block
const block = wp.blocks.createBlock( 
  'core/paragraph', { content: 'Hi Roy!' }
 );
//Insert that block
wp.data.dispatch( 'core/block-editor' ).insertBlocks( block );

If you run that in the console of a WordPress block editor, that will insert a paragraph block. In a plugin’s JavaScript file, here is what it would look like with imports:

import domReady from '@wordpress/dom-ready';
import {createBlock} from '@wordpress/blocks';
import {dispatch} from '@wordpress/data';
//Wait untill page is loaded
domReady( function () {
   //Create a paragrah block
  const block = createBlock( 
    'core/paragraph', { content: 'Hi Roy!' }
   );
  //Insert that block
  dispatch( 'core/block-editor' ).insertBlocks( block );
} );

Notice that I used the DOM Ready function to wait until the page loaded to dispatch. This will not work before then. You could bind this same function to a click handler or other event.

Packages Used

More Helpful Links

Featured image by Josh Pollock, via WordPress Photos

New eBook

Refactoring WordPress Plugins

The PHP Parts

 For experienced WordPress developers who are looking to improve the PHP in their plugins, use new modern best practices and adopt test-driven development.