8

Gutenberg's API is quiet obscure and I can't figure how to create and append a block to a post.

I've found the wp.blocks.createBlock('core/paragraph', {content: "blabla"}); which returns a pretty block object, but does not append any content to the post.

I would like to insert a simple paragraph with some custom content just by clicking a button.

Bastien Ho
  • 777
  • 12
  • 23

2 Answers2

18
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);
user9515876
  • 196
  • 1
  • 3
5

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

Erik Kubica
  • 1,180
  • 3
  • 15
  • 39
  • that file has moved to https://github.com/WordPress/gutenberg/blob/trunk/packages/block-editor/src/components/inserter/index.js (`master` was renamed to `trunk`) and the code has significantly changed, relevant is possibly https://github.com/WordPress/gutenberg/blob/44673e4b39110476581b4ccf8d5bc2b23f206e2a/packages/block-editor/src/components/inserter/index.js#L365 – Sandra Sep 20 '22 at 11:41