How To Insert Blocks In WordPress Block Editor

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

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 '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