What are block.json capabilities and how do you use apiVersion, supports, and usesContext?

So, you’re diving into the world of WordPress block development and you’ve stumbled across this block.json file. It seems a bit mysterious, doesn’t it? Like a little instruction manual for your block. The good news is, it’s not as complicated as it might appear.

At its core, block.json is where you tell WordPress: “Hey, this is my block, and here’s what it can do, what it needs, and how it fits into the wider WordPress ecosystem.” It’s the central configuration file that empowers your custom block with specific capabilities, making it play nicely with the block editor and other plugins. Think of it as the block’s ID card and its permission slip all rolled into one.

Let’s break down the key parts, starting with what apiVersion and supports are all about, and then we’ll get into the nitty-gritty of usesContext. By the end of this, you’ll have a solid grasp of how these elements shape your block’s behavior and make it a truly functional part of your WordPress site.

When you first look at a block.json file, you’ll likely see an apiVersion property. This might seem a little abstract, but it’s actually super important for keeping your block compatible and future-proof.

What is apiVersion For?

Basically, apiVersion tells WordPress which version of the Block Editor’s API your block is designed to work with. WordPress is always evolving, and the way blocks interact with the editor changes over time. This versioning ensures that as WordPress updates, your block knows how to behave correctly and doesn’t break unexpectedly.

Why Does It Matter for Developers?

If you’re building a block, setting the apiVersion correctly is like choosing the right blueprint for your house. You want to build it using the materials and techniques that are current and supported, so it stands strong for a long time.

  • Backward Compatibility: A higher apiVersion generally means your block is built using newer features and potentially assumes certain behaviors. If you set it too low, you might be missing out on modern functionalities or even encounter errors.
  • Forward Compatibility (sort of): While it doesn’t guarantee perfect compatibility with future WordPress versions (things change!), it signals to WordPress that your block is built with a certain level of the API in mind.
  • Plugin Interoperability: Other plugins and themes that interact with blocks also rely on these API versions. Setting it correctly ensures smoother integration.

What Values Can It Take?

Currently, the relevant apiVersion values are 2 and 3.

  • apiVersion: 2: This is the “older” but still widely supported version. Many existing blocks and older tutorials might refer to this. It’s a safe bet if you’re creating something with broader compatibility in mind or are working with older projects.
  • apiVersion: 3: This is the more recent version, introducing some new functionalities and changes to how certain things are handled. If you’re starting a new block development project and want to leverage the latest features, apiVersion: 3 is usually the way to go. You’ll find it allows for more sophisticated block behaviors.

It’s always a good idea to check the official WordPress developer documentation for the latest recommended apiVersion for new development.

In exploring the capabilities of block.json, it’s essential to understand how the parameters apiVersion, supports, and usesContext play a crucial role in defining the behavior and features of a block. For a deeper dive into optimizing web performance, you might find the article on Google PageSpeed Insights particularly useful, as it discusses various techniques to enhance your website’s speed and efficiency. You can read more about it in this article: Google PageSpeed Insights.

Defining Block Capabilities: supports

The supports property is where the magic really starts to happen in making your block dynamic and user-friendly. This is where you declare what built-in features of the block editor your block can utilize. Instead of building every little thing from scratch, supports lets you tap into features that WordPress already provides.

What Does supports Control?

Think of supports as a checklist of features your block can “support.” These are things like:

  • Colors: Can users change the text or background color of your block?
  • Typography: Can users adjust font sizes, families, or letter spacing?
  • Spacing: Can users control padding and margins?
  • Alignment: Can users align the block left, center, right, or wide/full width?
  • Custom Classes: Can users add their own CSS classes to the block for custom styling?
  • Reusable Blocks: Can your block be saved as a reusable block?
  • Removable: Can the block be deleted by the user?
  • Inserter: Should the block appear in the block inserter?

How to Use It in block.json

You define these capabilities as an object within your block.json file. Each property within this object is a specific feature, and you set its value to true if you want to enable it, or false (or omit it entirely) if you don’t.

“`json

{

“apiVersion”: 3,

“name”: “my-plugin/my-custom-block”,

“title”: “My Custom Block”,

“category”: “widgets”,

“icon”: “smiley”,

“description”: “A sample custom block.”,

“supports”: {

“html”: false,

“align”: [“wide”, “full”],

“color”: {

“background”: true,

“text”: true,

“link”: true

},

“spacing”: {

“padding”: true,

“margin”: true

},

“typography”: {

“fontSize”: true,

“textAlign”: true,

“lineHeight”: true

},

“reusable”: true

},

“textdomain”: “my-plugin”,

“editorScript”: “file:./index.js”,

“editorStyle”: “file:./index.css”,

“style”: “file:./style-index.css”

}

“`

In this example:

  • html: false means users won’t be able to edit the raw HTML of this block.
  • align: ["wide", "full"] enables wide and full-width alignment options for the block.
  • The color object allows users to change background, text, and link colors.
  • The spacing object enables control over padding and margin.
  • The typography object allows adjustments to font size, text alignment, and line height.
  • reusable: true makes the block eligible to be saved as a reusable block.

Fine-Grained Control with Nested Objects

For properties like color, spacing, and typography, you can go further and specify which aspects of that feature your block supports. For example, within color, you can choose to only enable background or text color controls, or both. This gives you a lot of flexibility in tailoring the user experience.

  • color.background: Enables the background color picker.
  • color.text: Enables the text color picker.
  • color.link: Enables the link color picker.
  • spacing.margin / spacing.padding: Enables controls for margin and padding.
  • typography.fontSize / typography.fontFamily / typography.fontStyle / typography.fontWeight / typography.lineHeight / typography.textAlign: Enables individual typography controls.

By carefully selecting what your block supports, you can significantly reduce the amount of custom code you need to write, while also providing a consistent and intuitive experience for users of the block editor.

The Power of Context: usesContext

This is where things get a bit more advanced and really highlight how blocks can interact with each other and with the broader WordPress environment. The usesContext property allows your block to access and respond to data from its parent blocks or the editor itself.

What is Block Context?

Imagine you have nested blocks, like a Group block containing a Paragraph block. The Group block might have certain settings, like a background color or a specific width. The Paragraph block, being inside the Group block, could potentially inherit or be aware of these settings. This awareness is what we call “context.”

usesContext is how you explicitly tell WordPress that your block needs access to certain pieces of this context data.

Why Would You Need usesContext?

There are many scenarios where this becomes incredibly useful:

  • Dynamic Styling: A child block might need to adjust its styling based on the parent’s background color or typography settings.
  • Conditional Logic: A block’s behavior might change depending on whether it’s inside a specific type of container block.
  • Data Sharing: Parent blocks can pass specific data down to child blocks.
  • Editor State Awareness: Blocks can react to changes in the editor’s overall state.

For example, if you have a custom quote block, you might want it to inherit the paragraph font size from its parent when it’s placed inside a Group block that has a specific font size applied. Or, if you have a gallery block that’s part of a custom layout, you might want child image blocks to know what the overall column count is.

How usesContext Works

You declare what context properties your block relies on. WordPress then makes these available to your block’s JavaScript.

“`json

{

“apiVersion”: 3,

“name”: “my-plugin/contextual-child-block”,

“title”: “Contextual Child Block”,

“category”: “widgets”,

“icon”: “awards”,

“description”: “A block that uses context.”,

“usesContext”: [

“postId”,

“postType”,

“color”,

“typography.fontSize”,

“align”

],

“textdomain”: “my-plugin”,

“editorScript”: “file:./index.js”,

“editorStyle”: “file:./index.css”,

“style”: “file:./style-index.css”

}

“`

In this example, contextual-child-block is declaring that it needs:

  • postId: The ID of the current post being edited.
  • postType: The type of the current post (e.g., ‘post’, ‘page’).
  • color: This is a bit more abstract and can refer to inherited color settings from parent blocks.
  • typography.fontSize: The font size that might be inherited from a parent block.
  • align: Information about the alignment of a parent block.

Accessing Context in JavaScript

Once you’ve declared usesContext in block.json, you can access these context values within your block’s JavaScript file. This typically happens in your edit function.

When registering your block using registerBlockType, you can pass a second argument to the edit function that contains the context values:

“`javascript

import { registerBlockType } from ‘@wordpress/blocks’;

import { __ } from ‘@wordpress/i18n’;

registerBlockType(‘my-plugin/contextual-child-block’, {

apiVersion: 3,

title: __(‘Contextual Child Block’, ‘my-plugin’),

icon: ‘awards’,

category: ‘widgets’,

description: __(‘A block that uses context.’, ‘my-plugin’),

usesContext: [

‘postId’,

‘postType’,

‘color’,

‘typography.fontSize’,

‘align’,

],

edit({ attributes, setAttributes, context }) {

// Accessing context values

const { postId, postType, color, fontSize, align } = context;

console.log(‘Current Post ID:’, postId);

console.log(‘Current Post Type:’, postType);

console.log(‘Inherited Color:’, color);

console.log(‘Inherited Font Size:’, fontSize);

console.log(‘Inherited Align:’, align);

// You can then use these values to conditionally render elements,

// apply styles, or modify attributes.

return (

This block is in post ID: {postId}

Post type: {postType}

{color &&

Inherited color: {color.background}

}

{fontSize &&

Inherited font size: {fontSize}px

}

{align &&

Inherited alignment: {align}

}

);

},

save() {

// The save function typically doesn’t need context directly,

// as it’s about the static HTML output.

return null;

},

});

“`

Common Contextual Values

Here are some of the most frequently used context values you might encounter or want to use:

  • postId / postType: Information about the current post. Useful for linking references or setting up unique IDs.
  • postTitle: The title of the current post.
  • postSlug: The slug of the current post.
  • editPost.title: The current value of the post title field in the editor.
  • isInSelectedBlock: A boolean indicating if the current block is within the selected block(s).
  • color: Can provide { background, text, link } objects if a parent block has these set.
  • typography.fontSize / typography.fontFamily etc.: Inherited typography settings.
  • align: Inherited alignment settings.
  • layout: Information about the layout of the parent container, especially useful for nested blocks within group or cover blocks.
  • orientation: For example, ‘horizontal’ or ‘vertical’ within certain container blocks.

The specific context keys available can evolve with WordPress core. It’s always best practice to check the official WordPress documentation for the most up-to-date list and how they are structured. usesContext is a powerful tool for creating more intelligent and interconnected blocks.

Advanced supports Options

While the basic supports properties cover a lot, there are some more granular controls and interesting options you can leverage to fine-tune your block’s functionality. This allows you to expose only the features that make sense for your specific block.

Typography Controls Deep Dive

As we hinted at earlier, the typography object within supports can be quite detailed. Instead of just true, you can specify which elements of typography are controllable:

  • fontSize: true / fontSize: { size: '1.5rem', range: [8, 72] }: Enables a font size control. You can define specific predefined sizes or a range for the user to pick from.
  • fontFamily: true / fontFamily: { revert: true }: Enables font family selection. revert: true would allow the user to reset to the default.
  • fontStyle: true / fontStyle: { italic: true, revert: true }: Enables control for italic styles.
  • fontWeight: true / fontWeight: { bold: true, revert: true }: Enables control for bold weights.
  • lineHeight: true / lineHeight: { unit: 'em', revert: true }: Enables control for line height. You can specify the unit (em, rem, px).
  • textAlign: true / textAlign: ['left', 'center', 'right', 'justify']: Allows text alignment control. You can restrict which alignment options are available.

“`json

“supports”: {

“typography”: {

“fontSize”: {

“size”: “1.75rem”, // A default size

“range”: [12, 60], // A min/max range in pixels

“fluid”: false // Set to true for a fluid font size experience

},

“textAlign”: [“left”, “center”, “right”],

“fontStyle”: {

“italic”: true,

“normal”: true

}

}

}

“`

This level of control ensures that your block’s settings panel only shows the options that are relevant and useful for that block, leading to a cleaner and less overwhelming user experience.

Spacing Options

Similar to typography, spacing offers a way to control how users can adjust margins and padding:

  • spacing.margin / spacing.padding: If set to true, it enables the default spacing controls in the block inspector.
  • spacing.margin: { fluid: true } / spacing.padding: { fluid: true }: This enables fluid spacing, where the spacing can adjust based on the viewport size.
  • spacing.margin: { top: true, bottom: true } / spacing.padding: { left: true, right: true }: You can specify which sides (top, bottom, left, right) individual padding or margin controls are enabled for.

“`json

“supports”: {

“spacing”: {

“padding”: {

“top”: true,

“bottom”: true,

“left”: true,

“right”: true,

“unit”: “rem” // Specify a preferred unit, e.g., ‘rem’ or ‘px’

},

“margin”: false // Explicitly disable margin controls if not needed

}

}

“`

By default, if spacing is true, it enables controls for all sides of both padding and margin. Being specific allows you to tailor this.

Anchor and Class Name Properties

  • anchor: true: This allows users to set an HTML anchor for the block. This is useful for creating links directly to that block from elsewhere on the page or from an external link. WordPress automatically generates the necessary id attribute for the block.
  • className: true: This enables a field in the block’s sidebar inspector where users can add custom CSS classes to the block. This is invaluable for advanced users or theme developers who want to apply further custom styling without modifying the block’s core code.

“`json

“supports”: {

“anchor”: true,

“className”: true

}

“`

When className is enabled, a “Advanced” panel appears in the block’s settings sidebar, allowing users to input custom class names.

block.json and apiVersion: 3 Specifics

With apiVersion: 3, there are a few more nuanced supports and context-related features emerging that are worth noting for future-proofing your development:

  • templateLock: This supports property, when set to true or a specific string like 'content' or 'insert', can prevent users from moving, deleting, or inserting blocks within a specific parent block (like a group or stack). This is useful for creating pre-defined layouts that shouldn’t be altered.
  • deriveStylesFromClassName: This is a more advanced opt-in that can be explored in newer WordPress versions. It relates to how block styles are generated and can offer performance benefits.

Always refer to the latest WordPress developer handbook for the most up-to-date list of supported supports properties and their accepted values, as this API continues to evolve.

Understanding the capabilities of block.json is essential for developers working with the WordPress block editor. This file defines various properties such as apiVersion, supports, and usesContext, which play a crucial role in how blocks function within the editor. For a deeper exploration of these concepts and their practical applications, you can refer to a related article that provides valuable insights and examples. Check out this informative piece on block.json capabilities to enhance your understanding and implementation skills.

The Relationship Between block.json and Development

It’s crucial to understand that block.json isn’t just a static configuration file; it directly influences how you write your block’s JavaScript and CSS, and how it behaves in the editor and on the frontend.

How block.json Guides JavaScript Development

The editorScript and editorStyle properties in block.json tell WordPress which JavaScript and CSS files to load specifically for the block editor. This is where you’ll do the heavy lifting of your block’s interactive features.

  • Example: If you set editorScript: "file:./index.js", WordPress knows to load index.js from the same directory as block.json when the block editor is active and your block is in view.
  • When you declare usesContext in block.json, as shown earlier, your edit function receives the context object containing that data. Your JavaScript then uses this data to render dynamic elements or apply conditional logic.
  • Features enabled in supports (like color, typography, spacing) will automatically render UI controls in the block’s sidebar inspector. Your JavaScript needs to be prepared to handle these attributes being passed down via setAttributes and attributes.

Frontend and Editor Styles

The style property in block.json specifies which CSS file should be loaded on both the frontend (when viewing the post/page) and in the editor. This is used for the fundamental styling of your block.

  • Example: style: "file:./style-index.css" means style-index.css will be enqueued everywhere your block appears.

If you need styles that only apply in the editor (e.g., for editor-specific UI elements or to ensure the editor closely mirrors the frontend), you use the editorStyle property.

  • Example: editorStyle: "file:./index.css" means index.css will only be loaded in the block editor.

This separation allows for cleaner, more efficient styling – you don’t load editor-specific styles when they aren’t needed.

block.json as the Single Source of Truth

By consolidating all this metadata in block.json, WordPress gains a comprehensive understanding of your block. This allows the editor interface to be built dynamically, offering users the features your block is designed to support without requiring manual configuration in every instance.

This single file acts as the foundation for:

  • Block Registration: WordPress uses it to register your block with the editor.
  • UI Generation: The presence of supports properties dictates which controls appear in the inspector.
  • Asset Loading: editorScript, editorStyle, and style properties determine which files are loaded.
  • Block Interoperability: usesContext allows your block to communicate with its environment.

In essence, you define what your block is and what it can do in block.json, and then your JavaScript and CSS build upon that definition to create the actual functionality and appearance.

usesContext vs. supports

It’s easy to sometimes confuse usesContext and supports, as they both deal with block capabilities, but they serve distinct purposes. Understanding the difference is key to designing well-behaved blocks.

supports: What Your Block Offers

supports is about the features that your block provides to the user. It’s a declaration of intent for the core block editor functionalities that your block can manage or that the user can leverage directly on your block.

  • Enabling controls: When you set color: true or spacing.padding: true in supports, you’re turning on specific UI controls in the block’s sidebar inspector. These controls allow the user to modify the attributes of your specific block instance.
  • User interaction: It’s primarily about giving the user the power to customize your block.
  • Example: If your MyButton block supports color.background: true, users can pick a background color for that specific button.

usesContext: What Your Block Needs or Observes

usesContext is about what your block needs to know from its surrounding environment. It’s how your block introspects its context and reacts to settings or data that are not directly applied to itself but are part of its parent or the editor.

  • Accessing data: When you declare usesContext: ['postId', 'typography.fontSize'], you’re telling WordPress, “Please give me access to the current postId and any inherited fontSize from a parent block.”
  • Environmental awareness: It’s about your block being aware of its surroundings and potentially adapting its behavior or appearance based on that awareness, without the user directly changing that external setting.
  • Example: If your QuoteBlock usesContext: ['typography.fontSize'], and it’s placed inside a Group block that has a font size of 20px applied, your QuoteBlock‘s JavaScript can access that 20px value and potentially style its content accordingly, even though the font size wasn’t set directly on the QuoteBlock itself.

The Interplay

These two properties often work hand-in-hand:

  1. A Parent Block supports a feature: For instance, a Group block might support color.background: true.
  2. The user customizes the Parent Block: The user picks a blue background for the Group block.
  3. A Child Block usesContext that feature: A child Paragraph block might declare usesContext: ['color'] or specifically usesContext: ['color.background'].
  4. The Child Block Reacts: In its edit function, the Paragraph block can now access the inherited blue background color from the Group block and apply styles to itself, perhaps to ensure readability or for aesthetic reasons.

So, supports is about what your block exposes for users to modify, while usesContext is about what your block observes or consumes from its environment. Both are fundamental to building sophisticated and interconnected Gutenberg blocks.