ブロックのコンテキストと通信
多くのブロックは独立しており、独自のフィールドとテンプレートを持ち、周囲のブロックを気にしません。一方、階層構造が自然なコンポーネントもあります。たとえば、親が列数と間隔を制御するカードグリッド、親が通貨を設定する料金表、子ブロックにライトテーマかダークテーマかを伝えるセクションラッパーなどです。
WordPressは、ブロックコンテキストAPIを提供します。親ブロックがデータの一部を公開し、子ブロックがそれを購読します。親が変更されると、子ブロックも自動的に更新されます。Blockstudioを使うと、これが大幅に簡単になります。providesContextを設定する必要はありません。すべてのBlockstudioブロックが、すべての属性をコンテキストとして自動的に提供します。子ブロック側では、block.jsonに1行追加するだけで購読できます。
このガイドでは、コンテキストを使った実用的なコンポーネントパターンを4つ作成し、それぞれ異なる連携のニーズを示します。
Blockstudioでのコンテキストの仕組み
標準のWordPressでは、まず親の各属性をprovidesContext内のコンテキストキーに明示的に対応付け、そのキーを子のusesContextに列挙する必要があります。Blockstudioでは、最初の手順が不要になります。
親ブロック: 設定は不要です。すべてのBlockstudioブロックが、ブロック名のもとですべての属性を自動的に提供します。
子ブロック: 親ブロックの名前を指定したusesContextを追加します。
{
"usesContext": ["my-theme/parent-block"]
}
子テンプレート:$context(または省略形の$c)を使って親の属性にアクセスします。
<?php $parent = $context['my-theme/parent-block']; ?>
<p>Parent says: <?php echo esc_html( $parent['message'] ); ?></p>
設定はこれだけです。親ブロックにprovidesContextを設定する必要も、属性を対応付ける必要も、登録コードもありません。子ブロックは変換済みの親属性をすべて受け取ります。メディアフィールドは添付ファイルのデータとして解決され、選択フィールドはreturnFormatに従い、リピーターは完全に展開されます。
2種類のコンテキスト
Blockstudioはテンプレートで2つのコンテキスト変数を提供します。それぞれ役割が異なります。
| 変数 | 内容 | 用途 |
|---|---|---|
$context / $c |
親ブロックの属性(usesContext経由) |
コンポーネント間の連携 |
$block['context'] / $b['context'] |
WordPressループのデータ(postId、postType) |
Queryブロックのループ |
1つ目はブロックから親ブロックへの情報伝達に使います。2つ目は、Queryループ内でレンダリング対象の投稿を知る必要があるブロック向けです。このガイドでは1つ目を扱います。
エディターでのサポート
エディターではコンテキストの更新がリアクティブに反映されます。ユーザーが親ブロックのフィールド値を変更すると、その親のコンテキストを購読しているすべての子ブロックが新しい値で自動的に再レンダリングされます。手動で更新する必要はありません。
セクションのラッパー
最も一般的なコンテキストの使い方は、子ブロックにテーマ設定を提供するラッパーブロックです。親ブロックには背景色、文字色、パディングのフィールドがあります。子ブロックはこれらの値を読み取り、一貫したスタイルを適用します。
親:セクション
{
"name": "my-theme/section",
"title": "Section",
"category": "design",
"icon": "align-wide",
"description": "Section wrapper with theme settings.",
"blockstudio": {
"attributes": [
{
"id": "theme",
"type": "select",
"label": "Theme",
"default": "light",
"options": [
{ "value": "light", "label": "Light" },
{ "value": "dark", "label": "Dark" },
{ "value": "accent", "label": "Accent" }
]
},
{
"id": "spacing",
"type": "select",
"label": "Spacing",
"default": "md",
"options": [
{ "value": "sm", "label": "Small" },
{ "value": "md", "label": "Medium" },
{ "value": "lg", "label": "Large" }
]
}
]
}
}
<?php
$theme_classes = array(
'light' => 'bg-white text-gray-900',
'dark' => 'bg-gray-900 text-white',
'accent' => 'bg-indigo-600 text-white',
);
$spacing_classes = array(
'sm' => 'py-8',
'md' => 'py-16',
'lg' => 'py-24',
);
$classes = ( $theme_classes[ $a['theme'] ] ?? '' ) . ' ' . ( $spacing_classes[ $a['spacing'] ] ?? '' );
?>
<div useBlockProps class="<?php echo esc_attr( $classes ); ?>">
<InnerBlocks
allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/section-heading', 'my-theme/section-text', 'core/columns', 'core/group' ) ) ); ?>'
/>
</div>
子:セクション見出し
{
"name": "my-theme/section-heading",
"title": "Section Heading",
"category": "design",
"icon": "heading",
"description": "Heading that adapts to section theme.",
"usesContext": ["my-theme/section"],
"parent": ["my-theme/section"],
"blockstudio": {
"attributes": [
{ "id": "text", "type": "text", "label": "Heading", "default": "Section Title" },
{
"id": "size",
"type": "select",
"label": "Size",
"default": "lg",
"options": [
{ "value": "sm", "label": "Small" },
{ "value": "lg", "label": "Large" },
{ "value": "xl", "label": "Extra Large" }
]
}
]
}
}
<?php
$section = $context['my-theme/section'] ?? array();
$theme = $section['theme'] ?? 'light';
$color_class = match ( $theme ) {
'light' => 'text-gray-900',
'dark' => 'text-white',
'accent' => 'text-white',
default => 'text-gray-900',
};
$size_class = match ( $a['size'] ) {
'sm' => 'text-2xl',
'lg' => 'text-4xl',
'xl' => 'text-6xl',
default => 'text-4xl',
};
?>
<h2 useBlockProps class="<?php echo esc_attr( "$color_class $size_class font-bold" ); ?>">
<?php echo esc_html( $a['text'] ); ?>
</h2>
この例でわかること: 見出しには独自の色フィールドがありません。コンテキストからセクションのthemeの値を読み取り、それに合わせて表示を変えます。エディターでユーザーがセクションを「ライト」から「ダーク」に切り替えると、見出しの文字色もすぐに更新されます。
子のblock.jsonにあるparentプロパティは、ブロックを挿入できる場所を制限します。ユーザーがmy-theme/sectionブロック内にいるときだけ、インサーターに表示されます。これは任意ですが、特定の親ブロック内でのみ意味を持つブロックには設定をおすすめします。
子:セクション本文
{
"name": "my-theme/section-text",
"title": "Section Text",
"category": "design",
"icon": "text",
"description": "Body text that adapts to section theme.",
"usesContext": ["my-theme/section"],
"parent": ["my-theme/section"],
"blockstudio": {
"attributes": [
{ "id": "text", "type": "textarea", "label": "Text", "default": "Section body text." }
]
}
}
<?php
$section = $context['my-theme/section'] ?? array();
$theme = $section['theme'] ?? 'light';
$color_class = match ( $theme ) {
'dark', 'accent' => 'text-white/80',
default => 'text-gray-600',
};
?>
<p useBlockProps class="<?php echo esc_attr( "$color_class text-lg leading-relaxed" ); ?>">
<?php echo esc_html( $a['text'] ); ?>
</p>
これで見出しと本文の両方がセクションのテーマに応じて変わります。親ブロックで一度テーマを選ぶだけで、すべての子ブロックに反映されます。
カードグリッド
カードの子ブロックのレイアウト設定を制御するグリッドの親ブロックです。親ブロックが列数と間隔を定義します。子ブロックはこれらの値からレイアウトを把握し、それに応じてスタイルを調整します。
親:カードグリッド
{
"name": "my-theme/card-grid",
"title": "Card Grid",
"category": "design",
"icon": "grid-view",
"description": "Responsive card grid with configurable columns.",
"blockstudio": {
"attributes": [
{
"id": "columns",
"type": "range",
"label": "Columns",
"default": 3,
"min": 1,
"max": 4,
"step": 1
},
{
"id": "gap",
"type": "select",
"label": "Gap",
"default": "md",
"options": [
{ "value": "sm", "label": "Small" },
{ "value": "md", "label": "Medium" },
{ "value": "lg", "label": "Large" }
]
},
{
"id": "cardStyle",
"type": "select",
"label": "Card Style",
"default": "elevated",
"options": [
{ "value": "elevated", "label": "Elevated (shadow)" },
{ "value": "outlined", "label": "Outlined (border)" },
{ "value": "flat", "label": "Flat (no decoration)" }
]
}
]
}
}
<?php
$gap_class = match ( $a['gap'] ) {
'sm' => 'gap-4',
'md' => 'gap-6',
'lg' => 'gap-8',
default => 'gap-6',
};
?>
<div useBlockProps class="grid grid-cols-<?php echo esc_attr( $a['columns'] ); ?> <?php echo esc_attr( $gap_class ); ?>">
<InnerBlocks
allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/card' ) ) ); ?>'
template='<?php echo esc_attr( wp_json_encode( array(
array( 'my-theme/card', array() ),
array( 'my-theme/card', array() ),
array( 'my-theme/card', array() ),
) ) ); ?>'
/>
</div>
子:カード
{
"name": "my-theme/card",
"title": "Card",
"category": "design",
"icon": "cover-image",
"description": "Card that inherits style from its grid parent.",
"usesContext": ["my-theme/card-grid"],
"parent": ["my-theme/card-grid"],
"blockstudio": {
"attributes": [
{ "id": "image", "type": "files", "label": "Image", "multiple": false },
{ "id": "title", "type": "text", "label": "Title", "default": "Card Title" },
{ "id": "description", "type": "textarea", "label": "Description", "default": "Card description goes here." },
{ "id": "url", "type": "link", "label": "Link" }
]
}
}
<?php
$grid = $context['my-theme/card-grid'] ?? array();
$card_style = $grid['cardStyle'] ?? 'elevated';
$style_class = match ( $card_style ) {
'elevated' => 'bg-white rounded-xl shadow-md',
'outlined' => 'bg-white rounded-xl border border-gray-200',
'flat' => 'bg-gray-50 rounded-xl',
default => 'bg-white rounded-xl shadow-md',
};
?>
<div useBlockProps class="<?php echo esc_attr( "$style_class overflow-hidden" ); ?>">
<?php if ( $a['image'] ) : ?>
<img
src="<?php echo esc_url( $a['image']['url'] ); ?>"
alt="<?php echo esc_attr( $a['image']['alt'] ); ?>"
class="w-full aspect-video object-cover" />
<?php endif; ?>
<div class="p-6">
<h3 class="text-lg font-semibold"><?php echo esc_html( $a['title'] ); ?></h3>
<p class="mt-2 text-gray-600"><?php echo esc_html( $a['description'] ); ?></p>
<?php if ( $a['url'] ) : ?>
<a href="<?php echo esc_url( $a['url']['url'] ); ?>" class="mt-4 inline-block text-indigo-600 font-medium">
<?php echo esc_html( $a['url']['title'] ?: 'Learn more' ); ?>
</a>
<?php endif; ?>
</div>
</div>
この例でわかること: カードには独自のスタイルフィールドがありません。グリッドの親ブロックからcardStyleを読み取ります。ユーザーがグリッドを「浮き出し」から「アウトライン」に切り替えると、グリッド内のすべてのカードが一度に更新されます。各カードを個別に更新しなくても、見た目の一貫性を保てます。
<InnerBlocks>のtemplate属性により、グリッドにはカードが3つあらかじめ配置され、ユーザーはそこから始められます。
料金表
親ブロックが通貨や請求期間などの共通ロジックを提供し、子ブロックが表示に使う、より高度なパターンです。これにより、料金プランごとに同じフィールドを重複して設定せずに済みます。
親:料金表
{
"name": "my-theme/pricing-table",
"title": "Pricing Table",
"category": "text",
"icon": "money-alt",
"description": "Pricing comparison with shared currency and billing settings.",
"blockstudio": {
"attributes": [
{
"id": "currency",
"type": "select",
"label": "Currency",
"default": "usd",
"options": [
{ "value": "usd", "label": "USD ($)" },
{ "value": "eur", "label": "EUR (\u20ac)" },
{ "value": "gbp", "label": "GBP (\u00a3)" }
]
},
{
"id": "period",
"type": "select",
"label": "Billing Period",
"default": "month",
"options": [
{ "value": "month", "label": "Monthly" },
{ "value": "year", "label": "Yearly" }
]
}
]
}
}
<div useBlockProps class="grid grid-cols-3 gap-6 items-start">
<InnerBlocks
allowedBlocks='<?php echo esc_attr( wp_json_encode( array( 'my-theme/pricing-tier' ) ) ); ?>'
template='<?php echo esc_attr( wp_json_encode( array(
array( 'my-theme/pricing-tier', array( 'name' => 'Starter', 'price' => 9 ) ),
array( 'my-theme/pricing-tier', array( 'name' => 'Pro', 'price' => 29, 'highlighted' => true ) ),
array( 'my-theme/pricing-tier', array( 'name' => 'Enterprise', 'price' => 99 ) ),
) ) ); ?>'
/>
</div>
子:料金プラン
{
"name": "my-theme/pricing-tier",
"title": "Pricing Tier",
"category": "text",
"icon": "tag",
"description": "Single pricing tier that reads currency from parent.",
"usesContext": ["my-theme/pricing-table"],
"parent": ["my-theme/pricing-table"],
"blockstudio": {
"attributes": [
{ "id": "name", "type": "text", "label": "Tier Name", "default": "Plan" },
{ "id": "price", "type": "number", "label": "Price", "default": 0 },
{ "id": "highlighted", "type": "toggle", "label": "Highlighted", "default": false },
{
"id": "features",
"type": "repeater",
"label": "Features",
"attributes": [
{ "id": "text", "type": "text", "label": "Feature" }
]
}
]
}
}
<?php
$table = $context['my-theme/pricing-table'] ?? array();
$currency = $table['currency'] ?? 'usd';
$period = $table['period'] ?? 'month';
$symbols = array(
'usd' => '$',
'eur' => "\u{20AC}",
'gbp' => "\u{00A3}",
);
$symbol = $symbols[ $currency ] ?? '$';
$period_label = $period === 'year' ? '/year' : '/month';
$border_class = $a['highlighted'] ? 'border-2 border-indigo-600' : 'border border-gray-200';
?>
<div useBlockProps class="<?php echo esc_attr( "rounded-xl p-8 $border_class" ); ?>">
<h3 class="text-lg font-semibold"><?php echo esc_html( $a['name'] ); ?></h3>
<div class="mt-4">
<span class="text-4xl font-bold"><?php echo esc_html( $symbol . $a['price'] ); ?></span>
<span class="text-gray-500"><?php echo esc_html( $period_label ); ?></span>
</div>
<?php if ( ! empty( $a['features'] ) ) : ?>
<ul class="mt-6 space-y-3">
<?php foreach ( $a['features'] as $feature ) : ?>
<li class="flex items-center gap-2">
<span class="text-indigo-600">✓</span>
<?php echo esc_html( $feature['text'] ); ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
この例でわかること: 通貨記号と請求期間は料金表で一度定義され、すべてのプランに引き継がれます。ユーザーがUSDからEURに切り替えると、3つすべてのプランの通貨記号が同時に更新されます。コンテキストがなければ、各プランに通貨フィールドを重複して設定し、手動で同期し続ける必要があります。
Queryループのコンテキスト
WordPressがQueryブロックのループ内で提供する、別種のコンテキストもあります。ブロックがループ内でレンダリングされると、$block['context'](または$b['context'])には現在の反復対象の投稿データが格納されます。
<?php
$loop_post_id = $block['context']['postId'];
$loop_post_type = $block['context']['postType'];
?>
<article useBlockProps>
<h2><?php echo esc_html( get_the_title( $loop_post_id ) ); ?></h2>
<p><?php echo esc_html( get_the_excerpt( $loop_post_id ) ); ?></p>
<a href="<?php echo esc_url( get_permalink( $loop_post_id ) ); ?>">Read more</a>
</article>
これは親ブロックのコンテキスト($context / $c)とは異なります。ループコンテキストはWordPressコアが提供し、postIdとpostTypeのみを含みます。このためにblock.jsonでusesContextを使う必要はありません。BlockstudioがすべてのブロックをpostIdとpostTypeに自動的に登録します。
ループコンテキストの用途: Queryブロック内のカスタム投稿カード、投稿メタデータを表示するブロック、ループ内で投稿ごとに表示を変える必要があるブロックなど。
ループコンテキストに関係なく、外側のページの投稿データにもアクセスできます。
$outer_post_id = $block['postId']; // always the current page
$loop_post_id = $block['context']['postId']; // current loop iteration
ネストされたコンテキスト
コンテキストは1階層だけでなく、ブロックツリー全体に伝わります。ブロックAの中にブロックBがあり、その中にブロックCがある場合、CはAのコンテキストを購読できます。WordPressがInnerBlocksのすべての階層にコンテキストを伝えるためです。
my-theme/section (theme: "dark")
└── core/columns
└── core/column
└── my-theme/section-heading (reads section context)
見出しはセクションの直接の子である必要はありません。コアブロック(カラム、グループなど)の中にネストされていても、セクションのコンテキストを受け取れます。usesContextの購読はどの深さでも機能します。
複数の親
子ブロックは複数の親ブロックを購読できます。
{
"usesContext": ["my-theme/section", "my-theme/card-grid"]
}
<?php
$section = $context['my-theme/section'] ?? array();
$grid = $context['my-theme/card-grid'] ?? array();
$theme = $section['theme'] ?? 'light';
$cardStyle = $grid['cardStyle'] ?? 'elevated';
?>
祖先ツリー内に親ブロックが見つからない場合、そのキーは$contextに含まれません。ブロックが想定外の親の外で使われる場合に備え、コンテキスト値を読むときは常にnull合体演算子(??)を使うか、isset()を確認してください。
防御的なコーディング
コンテキストを使うブロックは、親ブロックがない場合にも必ず対応する必要があります。ユーザーがブロックを意図された親の外に挿入したり、親ブロックの特定のフィールドに値が設定されていなかったりすることがあります。
<?php
// Always provide defaults
$section = $context['my-theme/section'] ?? array();
$theme = $section['theme'] ?? 'light';
$spacing = $section['spacing'] ?? 'md';
?>
子ブロックを親ブロック内でのみ表示するには、parentプロパティを追加します。
{
"parent": ["my-theme/section"]
}
これにより、ユーザーがmy-theme/sectionブロック内にいないときは、インサーターからそのブロックが非表示になります。parentがなければ、ブロックはどこにでも表示されるため、コンテキストがない場合に適切に処理する責任はテンプレート側にあります。
コンテナの外では意味をなさないブロック(料金プラン、カードグリッドの項目など)にはparentを使います。単独でも使えるものの、親ブロックから追加のスタイルを受け取るブロック(独立しても使えるセクション見出しなど)では省略します。
ヒント
コンテキストは読み取り専用です。 子ブロックはコンテキストを通じて親ブロックの属性を変更できません。データは下方向にのみ流れ、上方向には流れません。子ブロックから親ブロックに情報を伝えるには、別の方法(Interactivity APIを使ったサーバー共有状態や、投稿メタデータなど)が必要です。
すべての属性が提供されます。 Blockstudioは選択した属性だけでなく、親ブロックのすべての属性を提供します。そのため、子ブロックは親が定義する任意のフィールドにアクセスできます。親が後からフィールドを追加しても、設定を変更せずに子ブロックから自動的に利用できます。
変換済みの値。 コンテキスト値はBlockstudioの属性変換パイプラインを通ります。ファイルフィールドには添付ファイルの全データ(url、alt、width、height)が含まれ、選択フィールドにはreturnFormatが反映され、リピーターは再帰的に展開されます。親テンプレートの$aと同じデータ構造が得られます。
エディターでのリアクティブな更新。 ユーザーがエディターで親のフィールドを変更すると、子ブロックは自動的に再レンダリングされます。これはWordPressに組み込まれたコンテキスト伝播とReact useEffectを使い、コンテキストの変更を検知して子ブロックをサーバー側で再レンダリングします。
コンテキストは必要な分だけ使いましょう。 Blockstudioは親のすべての属性を自動的に提供しますが、子ブロックは実際に必要な値だけを読み取るようにします。これはパフォーマンス上の懸念ではなく、コードをわかりやすく保つためです。子ブロックが依存する親のフィールドを記録しておけば、後から読む開発者にも関係が伝わります。
次のステップ
- コンテキストリファレンス:テンプレート変数、ループコンテキスト、
$blockデータ構造について。 - InnerBlocks:
<InnerBlocks />コンポーネント、allowedBlocks、テンプレート、フロントエンドラッパーフィルターについて。 - Interactivityガイド:ブロック間のクライアント側のリアクティビティについて(Interactivity APIはコンテキストで対応できない、子から親への通信、ブロック間の状態共有、ユーザー操作による更新を扱います)。