블록 컨텍스트와 통신
대부분의 블록은 독립적으로 작동합니다. 자체 필드와 템플릿을 갖고 있으며 주변 요소에 영향을 받지 않습니다. 하지만 카드의 열 수와 간격을 부모가 제어하는 카드 그리드, 통화를 부모가 설정하는 가격표, 자식에게 밝은 테마나 어두운 테마를 사용할지 알려주는 섹션 래퍼처럼 계층 구조가 자연스러운 컴포넌트도 있습니다.
WordPress는 이를 위해 블록 컨텍스트 API를 제공합니다. 부모 블록은 일부 데이터를 노출하고 자식 블록은 이를 구독합니다. 부모가 바뀌면 자식이 자동으로 업데이트됩니다. Blockstudio를 사용하면 설정이 훨씬 간단해집니다. providesContext를 전혀 구성할 필요가 없습니다. 모든 Blockstudio 블록이 모든 속성을 컨텍스트로 자동 제공하므로 자식 블록은 block.json에 한 줄만 추가해 구독하면 됩니다.
이 가이드에서는 컨텍스트를 사용하는 네 가지 실제 컴포넌트 패턴을 만들며, 각 패턴은 서로 다른 통신 요구 사항을 보여줍니다.
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를 따르며, 반복기는 완전히 확장됩니다.
두 가지 컨텍스트 유형
Blockstudio는 템플릿에 서로 다른 용도로 쓰이는 두 가지 컨텍스트 변수를 제공합니다:
| 변수 | 포함 내용 | 사용 사례 |
|---|---|---|
$context / $c |
부모 블록 속성(usesContext를 통해 제공) |
컴포넌트 통신 |
$block['context'] / $b['context'] |
WordPress 루프 데이터(postId, postType) |
쿼리 블록 루프 |
첫 번째는 블록이 부모와 소통할 때 사용합니다. 두 번째는 쿼리 루프 안의 블록이 현재 렌더링 중인 게시물을 알아야 할 때 사용합니다. 이 가이드에서는 첫 번째 유형을 다룹니다.
편집기 지원
편집기에서 컨텍스트 업데이트는 반응형으로 작동합니다. 사용자가 부모 블록의 필드 값을 바꾸면 해당 부모의 컨텍스트를 구독하는 모든 자식 블록이 새 값으로 자동 다시 렌더링됩니다. 수동으로 새로 고칠 필요가 없습니다.
섹션 래퍼
가장 흔한 컨텍스트 패턴은 자식에게 테마 설정을 제공하는 래퍼 블록입니다. 부모에는 배경색, 텍스트 색상 및 패딩 필드가 있습니다. 자식은 이 값을 읽어 일관된 스타일을 적용합니다.
부모: 섹션
{
"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 속성은 그리드에 카드 세 개를 미리 채워 시작점을 제공합니다.
가격표
부모가 자식의 표시에 필요한 공통 비즈니스 로직(통화, 청구 주기)을 제공하는 더 고급 패턴입니다. 각 가격 등급에 같은 필드를 중복해서 만들 필요가 없습니다.
부모: 가격표
{
"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로 바꾸면 세 등급 모두의 통화 기호가 동시에 업데이트됩니다. 컨텍스트가 없으면 각 등급에 통화 필드를 복제하고 수동으로 동기화해야 합니다.
쿼리 루프 컨텍스트
WordPress가 쿼리 블록 루프 안에서 제공하는 별도의 컨텍스트 유형도 있습니다. 블록이 루프 안에서 렌더링되면 $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를 자동으로 구독하게 합니다.
루프 컨텍스트가 유용한 경우: 쿼리 블록 안의 사용자 지정 게시물 카드, 게시물 메타 데이터를 표시하는 블록, 또는 루프에서 게시물마다 다르게 렌더링해야 하는 모든 블록.
루프 컨텍스트와 관계없이 바깥 페이지의 게시물 데이터에도 접근할 수 있습니다:
$outer_post_id = $block['postId']; // always the current page
$loop_post_id = $block['context']['postId']; // current loop iteration
중첩 컨텍스트
컨텍스트는 한 단계에 그치지 않고 블록 트리 전체를 따라 전달됩니다. 블록 A에 블록 B가 있고, 블록 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는 컨텍스트로 처리할 수 없는 자식에서 부모로의 통신, 블록 간 상태 및 사용자 트리거 업데이트를 담당합니다).