Skip to main content
Block context enables ancestor blocks to provide values that descendent blocks within their hierarchy can consume. This allows blocks to share data without hard-coded values or explicit awareness of the provider.

Overview

Block context is especially useful in full-site editing where block content may depend on the context of the post in which it’s displayed. For example, a blogroll template showing multiple posts can use a single “Post Excerpt” block that displays content based on an inherited post ID. If you’re familiar with React Context, block context adopts similar concepts. The client-side implementation uses React Context, and context is also supported in server-side render_callback functions.

Providing context

A block provides context by mapping a context name to one of its attributes using the providesContext property.

In block.json

In JavaScript

Include a namespace in context names (e.g., my-plugin/recordId) to avoid conflicts with other plugins or WordPress core.

Consuming context

A block consumes context by declaring the context names it needs in the usesContext array.

In block.json

In JavaScript

Using context values

Once declared, context values are accessible in both JavaScript and PHP implementations.

JavaScript (edit function)

Context is provided as a property to the edit function:

PHP (render callback)

Context is available from the context property of the $block argument:
Block context is not available in the save function.

Complete example

This example creates a parent “record” block that provides a record ID to a child “record-title” block.

1. Create the block

2. Define the provider block

Edit src/index.js:

3. Create the edit component

Edit src/edit.js:

4. Create the save function

Edit src/save.js:

5. Test the block

When you type a number in the text box, the record-title block below displays the same number through context.

Context limitations

  • Context only supports values from block attributes
  • Context flows from ancestors to descendants only (one-way)
  • A block must explicitly declare context usage with usesContext
  • Context is not available in the save function

Use cases

Post context in templates

Query loop context

Custom context

Best practices

  • Use namespaced context names to avoid conflicts
  • Document available context for your blocks
  • Validate context values before using them
  • Provide fallback values when context is unavailable
  • Consider using InnerBlocks templates to ensure child blocks are present