Block API Updates in 5.5

Coauthored by @aduth and @gziolo.

BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. Categories

The block categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging. is no longer mandatory or doesn’t have to match an existing category slug during blocks’ registration. When that happens, a block is rendered in the inserter under the Uncategorized section.

The default set of block categories was updated.

The new set of block categories is:

  • Text
  • Media
  • Design
  • Widgets
  • Embeds
  • Reusable

Of the above, a few have remained unchanged: Widgets, Embeds, Reusable.

Mappings have been added to ensure that existing blocks will be assigned to as close as possible to an equivalent category in the new set:

  • Common → Text
  • Formatting → Text
  • Layout → Design

Note that if you update your blocks to one of the new block categories, your block may no longer register correctly in older versions of WordPress. If your pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party supports older versions, you should consider to check if a category is registered before using it:

In PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher:

global $post;
$has_formatting_category = in_array( 'formatting', wp_list_pluck( get_block_categories( $post ), 'slug' ) );

register_block_type( 'my-plugin/my-block', array(
   'category' => $has_formatting_category ? 'formatting' : 'media',
   
   // ...
) );

In JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/.:

var hasFormattingCategory = wp.blocks.getCategories().some( function( category ) {
   return category.slug === 'formatting';
} );

wp.blocks.registerBlockType( 'my-plugin/my-block', {
   category: hasFormattingCategory ? 'formatting' : 'media',

   // ...
} );

Block Type Metadata

To register a new block type using metadata that can be shared between JavaScript and PHP code, start by creating a block.json file. This file:

  • Gives a name to the block type.
  • Defines some important metadata about the registered block type (title, category, icon, description, keywords).
  • Defines the attributes of the block type.
  • Registers all the scripts and styles for your block type.

Example:

{
	"name": "my-plugin/notice",
	"title": "Notice",
	"category": "text",
	"parent": [ "core/group" ],
	"icon": "star",
	"description": "Shows warning, error or success notices…",
	"keywords": [ "alert", "message" ],
	"textdomain": "my-plugin",
	"attributes": {
		"message": {
			"type": "string",
			"source": "html",
			"selector": ".message"
		}
	},
	"providesContext": {
		"my-plugin/message": "message"
	},
	"usesContext": [ "groupId" ],
	"supports": {
		"align": true,
		"lightBlockWrapper": true
	},
	"styles": [
		{ "name": "default", "label": "Default", "isDefault": true },
		{ "name": "other", "label": "Other" }
	],
	"example": {
		"attributes": {
			"message": "This is a notice!"
		}
	},
	"editorScript": "file:./build/index.js",
	"script": "file:./build/script.js",
	"editorStyle": "file:./build/index.css",
	"style": "file:./build/style.css"
}

For more information on the APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways., see the documentation.

Block Context

Block context is a feature which enables ancestor blocks to provide values which can be consumed by descendant blocks within its own hierarchy. Those descendant blocks can inherit these values without resorting to hard-coded values and without an explicit awareness of the block which provides those values.

This is especially useful in full-site editing where, for example, the contents of a block may depend on the context of the post in which it is displayed. A blogroll template may show excerpts of many different posts. Using block context, there can still be one single “Post ExcerptExcerpt An excerpt is the description of the blog post or page that will by default show on the blog archive page, in search results (SERPs), and on social media. With an SEO plugin, the excerpt may also be in that plugin’s metabox.” block which displays the contents of the post based on an inherited post ID.

If you are familiar with React Context, block context adopts many of the same ideas. In fact, the client-side block editor implementation of block context is a very simple application of ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. Context. Block context is also supported in server-side render_callback implementations, demonstrated in the examples below.

Defining Block Context

Block context is defined in the registered settings of a block. A block can provide a context value, or consume a value it seeks to inherit.

Providing Block Context

A block can provide a context value by assigning a providesContext property in its registered settings. This is an object which maps a context name to one of the block’s own attributes. The value corresponding to that attribute value is made available to descendant blocks and can be referenced by the same context name. Currently, block context only supports values derived from the block’s own attributes. This could be enhanced in the future to support additional sources of context values.

record/block.json

{
	"name": "my-plugin/record",
	"attributes": {
		"recordId": {
			"type": "number"
		}
	},
	"providesContext": {
		"my-plugin/recordId": "recordId"
	}
}

As seen in the above example, it is recommended that you include a namespace as part of the name of the context key so as to avoid potential conflicts with other plugins or default context values provided by WordPress. The context namespace should be specific to your plugin, and in most cases can be the same as used in the name of the block itself.

Consuming Block Context

A block can inherit a context value from an ancestor provider by assigning a usesContext property in its registered settings. This should be assigned as an array of the context names the block seeks to inherit.

record-title/block.json

{
	"name": "my-plugin/record-title",
	"usesContext": [ "my-plugin/recordId" ]
}

Using Block Context

Once a block has defined the context it seeks to inherit, this can be accessed in the implementation of edit (JavaScript) and render_callback (PHP). It is provided as an object (JavaScript) or associative array (PHP) of the context values which have been defined for the block. Note that a context value will only be made available if the block explicitly defines a desire to inherit that value.

JavaScript

record-title/index.js

registerBlockType( 'my-plugin/record-title', {
	edit( { context } ) {
		return 'The current record ID is: ' + context[ 'my-plugin/recordId' ];
	},
} );

PHP

A block’s context values are available from the context property of the $block argument passed as the third argument to the render_callback function.

record-title/index.php

register_block_type( 'my-plugin/record-title', array(
	'render_callback' => function( $attributes, $content, $block ) {
		return 'The current record ID is: ' . $block->context['my-plugin/recordId'];
	},
) );

#5-5, #block-editor, #dev-notes

Various changes to WordPress React Components in WordPress 5.5

BlockPreview component

In previous versions, when using the BlockPreview component, setting a height for the container was necessary in order to show the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. preview properly. This was not working properly in situations where the height of the content was dynamic and changing from preview to another.

In WordPress 5.5, the BlockPreview component automatically scales the content to the available width and adapts its height to its content height.

In most situations, this will improve the rendering of BlockPreview components but if you used to rely on the fixed heights, you should consider checking whether the new behavior is working properly.

Popover component

On WordPress 5.5, the Popover component has different default values for the noArrow and position props. If you relied on the previous default behavior, you must explicitly assign these props.

<Popover noArrow={ false } position="top center" /> 

#5-5, #block-editor, #dev-notes

New Block Tools on WordPress 5.5

In WordPress 5.5, the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. blocks continue to evolve with the addition of new blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. tools.

Custom Line Heights

Users can define custom line heights for headings and paragraphs. Themes can opt-in into this feature by defining the custom-line-height theme support flag.

add_theme_support( 'custom-line-height' );

Custom Units

In addition to pixels, users can now use other units to define the height of Cover blocks. The available units are: px, em, rem, vh, vw. Themes can opt-in into this feature by defining the custom-units theme support flag.

add_theme_support( 'custom-units' );

Themes can also filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. the available custom units.

add_theme_support( 'custom-units', 'rem', 'em' );

#5-5, #block-editor, #dev-notes

Block Patterns in WordPress 5.5

In WordPress 5.5, the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor introduces a new concept called block patterns. The goal is to allow users to build and share predefined block layouts, ready to insert and tweak more easily.

You can find the registered block patterns on the block inserter and add them to your post/page like any other block.

Block Patterns Registration

WordPress 5.5 comes with a number of built-in block patterns but it’s also possible for third-party plugins and themes to register additional block patterns or remove existing ones.

To register a custom block pattern, you can call the register_block_pattern function receives the name of the pattern as the first argument and an array describing properties of the pattern as the second argument. The properties of the block pattern include a title, a description, a categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging., potentially some additional keywords, and the content of the pattern.

function my_plugin_register_block_patterns() {
	register_block_pattern(
		'my-plugin/my-awesome-pattern',
		array(
			'title'       => __( 'Two buttons', 'my-plugin' ),
			'description' => _x( 'Two horizontal buttons, the left button is filled in, and the right button is outlined.', 'Block pattern description', 'my-plugin' ),
			'categories'  => array( 'buttons' ),
			'content'     => "<!-- wp:buttons {\"align\":\"center\"} -->\n<div class=\"wp-block-buttons aligncenter\"><!-- wp:button {\"backgroundColor\":\"very-dark-gray\",\"borderRadius\":0} -->\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link has-background has-very-dark-gray-background-color no-border-radius\">" . esc_html__( 'Button One', 'my-plugin' ) . "</a></div>\n<!-- /wp:button -->\n\n<!-- wp:button {\"textColor\":\"very-dark-gray\",\"borderRadius\":0,\"className\":\"is-style-outline\"} -->\n<div class=\"wp-block-button is-style-outline\"><a class=\"wp-block-button__link has-text-color has-very-dark-gray-color no-border-radius\">" . esc_html__( 'Button Two', 'my-plugin' ) . "</a></div>\n<!-- /wp:button --></div>\n<!-- /wp:buttons -->",
		)
	);
}

add_action( 'init', 'my_plugin_register_block_patterns' );


It is also possible to register custom categories for your own block patterns.

Refer to the block patterns documentation for more details about these APIs.

CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Block Patterns

While WordPress comes with a number of block patterns built-in, theme authors might want to opt-out of the bundled patterns and provide their own set.

You can do so by removing the core-block-patterns theme support flag.

remove_theme_support( 'core-block-patterns' );

#5-5, #block-editor, #dev-notes