Skip to content

Instantly share code, notes, and snippets.

@Shizumi

Shizumi/smzberg.js Secret

Created Nov 5, 2019
Embed
What would you like to do?
WordCampTokyo2019 登壇用デモ
let crel = wp.element.createElement;
wp.hooks.addFilter(
'blocks.getSaveElement',
'smzberg-boilerplate/heading',
( element, blockType, blockAttributes ) => {
if ( 'core/heading' === blockType.name ) {
// 見出し要素の保存形式を変更する
return crel(
'div',
{ className: 'grid-x' },
crel( 'div', { className: 'cell' }, element )
);
}
return element;
}
);
( function ( blocks, editor, element ) {
let RichText = editor.RichText;
blocks.registerBlockType(
'smzberg-custom/example',
{
title: 'Example Basic',
icon: 'universal-access-alt',
category: 'layout',
attributes: {
title: {
type: 'array',
source: 'children',
selector: 'h4'
},
address: {
type: 'array',
source: 'children',
selector: 'p',
}
},
edit: props => {
let title = props.attributes.title;
let address = props.attributes.address;
const onChangeTitle = newContent => {
props.setAttributes( { title: newContent } );
};
const onChangeAddress = newContent => {
props.setAttributes( { address: newContent } );
};
return [
crel(
RichText,
{
tagName: 'h4',
ClassName: props.className,
onChange: onChangeTitle,
value: title,
},
),
crel(
RichText,
{
tagName: 'p',
ClassName: props.className,
onChange: onChangeAddress,
value: address,
},
)
];
},
save: props => {
let title = props.attributes.title;
let address = props.attributes.address;
return crel(
'div',
{ className: 'grid-x' },
[
crel(
'div',
{ className: 'cell small-12' },
crel(
RichText.Content,
{
tagName: 'h4',
value: title,
}
)
),
crel(
'div',
{ className: 'cell small-12' },
crel(
RichText.Content,
{
tagName: 'p',
value: address,
}
)
)
]
);
},
} );
}( window.wp.blocks, window.wp.editor, window.wp.element ) );
<?php
/**
* Plugin Name: SMZCustomBlockEditor
*
* @package SMZCustomBlockEditor
* @since 1.0.0
*/
function smzberg_boilerplate_block() {
wp_register_script(
'smzberg-custom-block',
plugins_url( 'js/smzberg.js', __FILE__ ),
[ 'wp-blocks', 'wp-element', 'wp-editor' ]
);
register_block_type(
'smzberg-boilerplate/heading',
[ 'editor_script' => 'smzberg-custom-block', ]
);
}
add_action( 'init', 'smzberg_boilerplate_block' );
function smzberg_register_block() {
register_block_type(
'smzberg-custom/example',
[ 'editor_script' => 'smzberg-custom-block', ]
);
}
add_action( 'init', 'smzberg_register_block' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment