How to "manually" (programmatically) insert a block in Gutenberg? How to "manually" (programmatically) insert a block in Gutenberg? wordpress wordpress

How to "manually" (programmatically) insert a block in Gutenberg?


var content = "Test content";var el = wp.element.createElement;var name = 'core/paragraph';// var name = 'core/html';insertedBlock = wp.blocks.createBlock(name, {    content: content,});wp.data.dispatch('core/editor').insertBlocks(insertedBlock);


Maybe this source code can help https://github.com/WordPress/gutenberg/blob/master/editor/components/inserter/index.js

Look at the end of the file for the part

onInsertBlock: ( item ) => {        const { insertionPoint, selectedBlock } = ownProps;        const { index, rootUID, layout } = insertionPoint;        const { name, initialAttributes } = item;        const insertedBlock = createBlock( name, { ...initialAttributes, layout } );        if ( selectedBlock && isUnmodifiedDefaultBlock( selectedBlock ) ) {            return dispatch( 'core/editor' ).replaceBlocks( selectedBlock.uid, insertedBlock );        }        return dispatch( 'core/editor' ).insertBlock( insertedBlock, index, rootUID );    },

To be more specific

return dispatch( 'core/editor' ).insertBlock( insertedBlock, index, rootUID );

Hope helps figuring out your problem, since it´s doing the same thing you want to achieve