概要
- Gutenberg ブロックにカスタムコントロール(カラー選択など)を追加する例を示します。カスタムコントロールを追加することで、ユーザーがブロックの外観を柔軟にカスタマイズできるようになります。
- このスニペットを利用するには、WordPress テーマやプラグイン開発の基本的な知識が必要です。
サンプルコード
function custom_block_register() {
register_block_type(
'my-plugin/custom-block',
array(
'attributes' => array(
'backgroundColor' => array(
'type' => 'string',
'default' => '#ffffff',
),
),
'render_callback' => 'custom_block_render',
)
);
}
add_action('init', 'custom_block_register');
function custom_block_render($attributes) {
$backgroundColor = $attributes['backgroundColor'];
return '<div style="background-color: ' . esc_attr($backgroundColor) . ';">Custom Block Content</div>';
}
解説
- `custom_block_register` 関数は、カスタムブロックを登録するための関数です。`attributes` に `backgroundColor` というカスタム属性を定義しています。
- `custom_block_render` 関数は、ブロックのレンダリングを行うコールバック関数です。`backgroundColor` を取得して、その色で背景色を設定したコンテンツを返します。
ベストプラクティス
- カスタムコントロールを追加する際は、ユーザビリティを考慮してシンプルなインターフェースを提供することが重要です。
- カスタムコントロールには、色選択ツールやスライダーなど、ユーザーが直感的に操作できるUI要素を組み込むことで、使いやすいブロックを作成できます。