ブロックバインディングAPIを使用して、カスタムフィールドの値を表示するブロックを作成します。
コンテンツ
ブロックの雛形を生成する
npx @wordpress/create-block@latest preset-block-bindings --template @block-developer-cookbook/preset-block-bindings
ブロックの構成
- preset-block-bindings
- build
- node_mojules
- src
- block-binding-shortcut.js
- block.json
- and more…
- preset-block-bindings.php
block.json
{
"$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3,
"name": "block-developers-cookbook/preset-block-bindings",
"version": "1.0.2",
"title": "Preset Block Bindings",
"category": "widgets",
"description": "Using a block variation to preset block bindings.",
"example": {},
"textdomain": "preset-block-bindings",
"editorScript": "file:./index.js",
"editorStyle": "file:./index.css",
"style": "file:./style-index.css"
}
preset-block-bindings.php
カスタムメタ情報を登録する場合、テーマのfunctions.phpではなく、プラグインのphpファイルからも登録できる。
/**
* Register custom post meta for block binding
*/
add_action('init', function () {
register_post_meta(
'post',
'my_custom_data',
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can('edit_posts');
},
'default' => 'This is a default value',
)
);
});
add_action(‘init’, function () {…})
- init アクション:WordPress の初期化処理が完了した後に実行されるフックで、このタイミングでプラグインやテーマの設定を追加したり、カスタム投稿タイプやメタデータの登録などを行う
register_post_meta(…)
register_post_meta
は、指定された投稿タイプにカスタムメタデータを登録するための関数- 投稿タイプ :メタデータを登録する対象となる投稿タイプを指定。この場合、
post
タイプの投稿にmy_custom_data
というカスタムメタデータを追加することを意味 - メタキー:
my_custom_data
は、投稿に関連付けられるカスタムメタデータの名前(キー)です。このキーを使って投稿のメタデータを取得・更新する - 引数の設定(配列)
show_in_rest
:true
の場合、このカスタムメタデータが REST API を通じて公開される。これにより、WordPress の ブロックエディタ(Gutenberg)や他の REST API クライアントからこのデータにアクセスできる。single
:true
の場合、このメタデータが単一の値(文字列、数値、ブール値など)として保存されることを意味します。false
に設定すると、配列として複数の値を保存するtype
:このカスタムメタデータがどのタイプのデータであるかを指定。この例では'string'
となっており、文字列としてデータが保存されることを意味。auth_callback
:認証チェック を行うためのコールバック関数。この関数内で、カスタムメタデータの読み取りや書き込みを行うユーザーが、特定の権限を持っているかどうかを確認する。
ここではcurrent_user_can('edit_posts')
を使って、現在のユーザーが「投稿を編集できる」権限を持っているかをチェックしているdefault
:このメタデータに値が設定されていない場合に使用されるデフォルト値を指定
block-binding-shortcut.js
段落ブロックのバリエーションとして、カスタムメタ情報を表示する。
/**
* WordPress dependencies
*/
import { registerBlockVariation } from '@wordpress/blocks';
/**
* Register a paragraph block variation with meta binding
*/
registerBlockVariation( 'core/paragraph', {
name: 'show-my-data',
title: 'Show My Data',
description: 'Display custom meta data in a paragraph',
attributes: {
metadata: {
bindings: {
content: {
source: 'core/post-meta',
args: {
key: 'my_custom_data',
},
},
},
},
},
isActive: [ 'metadata.bindings.content.args.key' ],
scope: [ 'inserter', 'transform' ],
} );
registerBlockVariation
- Gutenberg ブロックのバリエーションを登録するための関数
core/paragraph
というブロックに対して新しいバリエーション(show-my-data
)を登録している
import { registerBlockVariation } from '@wordpress/blocks';
registerBlockVariationの呼び出し
name
:バリエーションを識別する名前title
:バリエーションの表示名description
:このバリエーションの説明attributes
:バリエーションが持つ属性を設定。metadata
という属性にbindings
を使ってcontent
を設定しているmetadata.bindings.content
:ブロックのコンテンツ部分を指定。このコンテンツは、指定されたカスタムメタデータ(my_custom_data)にバインディング(結びつけ)されるsource
:データのソースを指定しています。core/post-meta
は、WordPress の投稿メタデータからデータを取得する意味args
:key: 'my_custom_data'
が指定されており、これによってこのバリエーションは、投稿に関連するカスタムメタデータmy_custom_data
を取得するように設定。このカスタムメタデータが段落ブロックのコンテンツとして表示されるisActive
:バリエーションがアクティブであるかどうかを決定する条件を設定。このコードでは、'metadata.bindings.content.args.key'
という条件が指定されており、my_custom_data
が存在する場合にこのバリエーションがアクティブになります。要するに、投稿にmy_custom_data
メタデータが存在すれば、このバリエーションが使用可能となる。scope
:バリエーションがどの状況で使用可能かを設定。'inserter'
:ブロック挿入時に表示されることを意味。つまり、ユーザーが新しいブロックを挿入する際に、このバリエーションが選択可能となります。'transform'
は、他のブロックからこのバリエーションへの変換が可能であることを意味
ブロックのプロパティをソースコード内のキーにバインドしているのは次の部分
attributes: {
metadata: {
bindings: {
content: {
source: 'core/post-meta',
args: {
key: 'my_custom_data',
},
},
},
},
},
ブロックが段落ブロックそのものなのか、それともこのバリエーションなのかを判別するのは次の部分
isActive: [ 'metadata.bindings.content.args.key' ],
挿入時のコード
既存の段落ブロックの拡張のため、フロントエンドを表示するsave.jsやrender.phpを作成していなくても、フロントエンドにデータが表示される。
コードエディタ
<!-- wp:paragraph {"metadata":{"bindings":{"content":{"source":"core/post-meta","args":{"key":"my_custom_data"}}}}} -->
<p></p>
<!-- /wp:paragraph -->
編集画面
<p role="document" aria-multiline="true" aria-readonly="true" tabindex="0" class="block-editor-rich-text__editable block-editor-block-list__block wp-block is-selected wp-block-paragraph rich-text" id="block-55409a5c-c50c-4faa-a53d-e22c85dd86f3" aria-label="ブロック: 段落" data-block="55409a5c-c50c-4faa-a53d-e22c85dd86f3" data-type="core/paragraph" data-title="Show My Data" data-empty="false" contenteditable="false" data-wp-block-attribute-key="content" style="--wp-admin-theme-color: var(--wp-block-synced-color); --wp-admin-theme-color--rgb: var(--wp-block-synced-color--rgb); white-space: pre-wrap; min-width: 1px;">更新するよ</p>
フロントエンド
<p>更新するよ</p>
段落ブロックのバリエーションを複数作成する場合
preset-block-bindings.php
add_action('init', function () {
// 1点目
register_post_meta(
'post',
'my_custom_data',
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can('edit_posts');
},
'default' => 'This is a default value',
)
);
// 2点目
register_post_meta(
'post',
'my_custom_data_2',
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can('edit_posts');
},
'default' => 'This is a default value 2',
)
);
});
block-binding-shortcut.js
/**
* WordPress dependencies
*/
import { registerBlockVariation } from '@wordpress/blocks';
/**
* Register a paragraph block variation with meta binding
*/
registerBlockVariation( 'core/paragraph', {
name: 'show-my-data',
title: 'Show My Data',
description: 'Display custom meta data in a paragraph',
attributes: {
metadata: {
bindings: {
content: {
source: 'core/post-meta',
args: {
key: 'my_custom_data',
},
},
},
},
},
isActive: [ 'metadata.bindings.content.args.key' ],
scope: [ 'inserter', 'transform' ],
} );
registerBlockVariation( 'core/paragraph', {
name: 'show-my-data-2',
title: 'Show My Data 2',
description: 'Display custom meta data in a paragraph 2',
attributes: {
metadata: {
bindings: {
content: {
source: 'core/post-meta',
args: {
key: 'my_custom_data_2',
},
},
},
},
},
isActive: [ 'metadata.bindings.content.args.key' ],
scope: [ 'inserter', 'transform' ],
} );
リファクタリング
preset-block-bindings.php
add_action('init', function () {
// メタデータ設定リスト
$meta_data = [
['my_custom_data', 'This is a default value'],
['my_custom_data_2', 'This is a default value 2'],
// 必要に応じて追加
];
// メタデータ登録用関数
$register_meta = function ($meta_key, $default_value) {
register_post_meta(
'post',
$meta_key,
array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can('edit_posts');
},
'default' => $default_value,
)
);
};
// すべてのメタデータを登録
foreach ($meta_data as $data) {
$register_meta($data[0], $data[1]);
}
});
block-binding-shortcut.js
/**
* WordPress dependencies
*/
import { registerBlockVariation } from '@wordpress/blocks';
/**
* Register a paragraph block variation with meta binding
*/
// 共通設定を持つバリエーション登録用関数
const registerMetaVariation = (name, title, description, metaKey) => {
registerBlockVariation('core/paragraph', {
name: name,
title: title,
description: description,
attributes: {
metadata: {
bindings: {
content: {
source: 'core/post-meta',
args: {
key: metaKey,
},
},
},
},
},
isActive: ['metadata.bindings.content.args.key'],
scope: ['inserter', 'transform'],
});
};
// メタデータごとにバリエーションを登録
registerMetaVariation('show-my-data', 'Show My Data', 'Display custom meta data in a paragraph', 'my_custom_data');
registerMetaVariation('show-my-data-2', 'Show My Data 2', 'Display custom meta data in a paragraph 2', 'my_custom_data_2');
参考:https://blockdevelopercookbook.com/recipes/preset-block-bindings-with-variations/