Gutenbergカスタムブロックその2
Gutenbergのカスタムブロックを制作します。
今回は、前回の続きで、pブロック内のテキストを編集可能なカスタムブロックです。
pluginディレクトリに専用のフォルダを好きな名前で用意してください。(今回の場合はgutenberg-custom-block-sample02)
プラグインフォルダ内のphpファイルのコードです。(gutenberg-custom-block-sample02.php)
<?php
/*
Plugin Name: Gutenberg Custom Block Sample02
Plugin URI:
Description:
Version: 1.0.0
Author: ETERNITY DESIGN
Author URI: https://eternitydesign.net/
*/
defined( 'ABSPATH' ) || exit;
function gutenberg_sample02_register_block() {
if(!function_exists( 'register_block_type' ) ) {
// Gutenbergがアクティブでない場合
return;
}
// block.jsをロードするように
wp_register_script(
'gutenberg-custom-block-sample02',
plugins_url('block.js', __FILE__),
array('wp-blocks', 'wp-element'),
filemtime( plugin_dir_path( __FILE__ ) . 'block.js')
);
// カスタムブロックの登録
register_block_type('ed-gutenberg-samples/sample02', array(
'script' => 'gutenberg-custom-block-sample02',
));
}
add_action('init', 'gutenberg_sample02_register_block');
?>
今回のPHPコードについては、
前回のものと内容にほとんど変化がなくsample02の箇所が異なるだけです。
次にblock.jsというファイルを同じディレクトリに用意します。
(function(blocks, element) {
var el = element.createElement;
blocks.registerBlockType('ed-gutenberg-samples/sample02', {
title: 'サンプル02',
// https://developer.wordpress.org/resource/dashicons/#tagcloud
icon: 'universal-access-alt',
// common, formatting, layout, widgets, embed
category: 'layout',
attributes: {
content: {
type: 'array',
source: 'children',
selector: 'p',
},
},
edit: function(props) {
var content = props.attributes.content;
function onChangeContent( newContent ) {
props.setAttributes({
content: newContent
});
}
return el(
wp.editor.RichText,
{
tagName: 'p',
className: props.className,
onChange: onChangeContent,
value: content,
}
);
},
save: function(props) {
return el(
wp.editor.RichText.Content,
{
tagName: 'p',
value: props.attributes.content,
}
);
}
} );
}(
window.wp.blocks,
window.wp.element
));
大きく異なるのはJSのほうです。
以下、簡単な解説です。
attributes
ここでは、pタグ中身となるコンテンツの種類を定義します。
今回はリッチテキストなので、arrayとchildrenが必要なようです。
edit
リッチテキストなので、wp.editor.RichTextを返すようにしている。
またonChangeイベントでsetAttributesを利用してコンテンツ内容を変更しています。(ざっくりというと)
save
こちらもwp.editor.RichTextをエレメントとして返しています。
単純なテキスト変更できるだけのものを用意するならざっとこんな感じ。