Gutenberg Patterns - markhowellsmead/helpers GitHub Wiki

In WordPress, Gutenberg Patterns are pre-defined collections of Blocks which can be inserted into the Block Editor using a single action by an author. For example, clicking a button or preview image.

The quickest way to try this out is to copy and paste the following examples into the browser's JavaScript console when the Block Editor is open.

Example code

Insert Blocks created on-the-fly

You have to create a separate Block object for each Block. If you don't, and insert e.g. paragraphBlock in the following example more than once, then you'll create a problem. This is because each Block object has the same clientID and so the Editor will see multiple instances of the same Block.

let headingBlock = wp.blocks.createBlock('core/heading', {level:1,content: 'Lorem Ipsum',align:'center'});
let paragraphBlock = wp.blocks.createBlock('core/paragraph', {content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'});

// EITHER insert after the last Block in the Post Content
wp.data.dispatch('core/block-editor').insertBlocks([
	headingBlock, paragraphBlock
]);

// OR insert at the top of the Post Content
wp.data.dispatch('core/block-editor').insertBlocks([
	headingBlock, paragraphBlock
], 0);

Insert HTML markup

let htmlMarkup = '<h2>My Headline</h2><ul><li>Item 1</li><li>Item 2</li></ul>';
let newBlocks = wp.blocks.rawHandler({HTML: htmlMarkup});
wp.data.dispatch('core/editor').insertBlocks(newBlocks);

Sample HTML

⚠️ **GitHub.com Fallback** ⚠️