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-siderender_callback functions.
Providing context
A block provides context by mapping a context name to one of its attributes using theprovidesContext 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 theusesContext 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 theedit function:
PHP (render callback)
Context is available from thecontext property of the $block argument:
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
Editsrc/index.js:
3. Create the edit component
Editsrc/edit.js:
4. Create the save function
Editsrc/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
savefunction
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