Skip to content

Instantly share code, notes, and snippets.

@zgordon
Last active May 30, 2021 01:09
Show Gist options
  • Save zgordon/0e06268a5d998b2ec79447febe9e67ec to your computer and use it in GitHub Desktop.
Save zgordon/0e06268a5d998b2ec79447febe9e67ec to your computer and use it in GitHub Desktop.
Example of how to use registerBlockType() to create a custom block in WordPress https://wp.zacgordon.com/2017/12/28/how-to-use-to-registerblocktype-to-create-blocks-in-wordpress/
// Get helper functions from global scope
const { registerBlockType } = window.wp.blocks;
const { __ } = window.wp.i18n;
// Use registerBlockType to create a custom block
registerBlockType(
'example-plugin/example-custom-block',
{
// Localize title using wp.i18n.__()
title: __( 'Block Title' ),
// Category Options: common, formatting, layout, widgets, embed
category: 'common',
// Dashicons Options - https://goo.gl/aTM1DQ
icon: 'wordpress-alt',
// Limit to 3 Keywords / Phrases
keywords: [
__( 'Example' ),
__( 'Project' ),
__( 'Code Samples' )
],
// Attributes set for each piece of dynamic data used in your block
attributes: {
exampleContent: {
type: 'array',
source: 'children',
selector: 'div.my-content',
},
},
// Determines what is displayed in the editor
edit: props => {
const onChangeContent = value => {
props.setAttributes( { exampleContent: value } );
};
return (
<div className={props.className}>
<Editable
tagname="div"
multiline="p"
className="my-content"
placeholder={ __( 'Add your content...' ) }
value={props.attributes.exampleContent}
onChange={onChangeContent}
/>
</div>
);
},
// Determines what is displayed on the frontend
save: props => {
return (
<div className={props.className}>
{props.attributes.exampleContent}
</div>
);
},
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment