Performance Chat Agenda: 5 March 2024

Here is the agenda for this week’s performance team meeting scheduled for Mar 5, 2024 at 16:00 UTC.

  • Announcements
    • Welcome to our new members of #core-performance
    • WordCampWordCamp WordCamps are casual, locally-organized conferences covering everything related to WordPress. They're one of the places where the WordPress community comes together to teach one another what they’ve learned throughout the year and share the joy. Learn more. Asia is this week
    • Updated agenda format to match CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. dev chat as suggested in previous chats
    • Reminder on timezone difference for the next 3 weeks, this chat will remain at 16:00 UTC
  • Priority items
    • WordPress performance TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. tickets discussion
    • Performance Lab 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 (and other performance plugins) discussion
    • Active priority projects
      • Plugin checker
      • Improve template loading
      • INP opportunities research
  • Open floor

If you have any topics you’d like to add to this agenda, please add them in the comments below.


This meeting happens in the #core-performance channel. To join the meeting, you’ll need an account on the Make WordPress Slack.

#agenda, #meeting, #performance, #performance-chat

Unification of the site and post editors in 6.5

In WordPress 6.5, the site editor has been refactored to match the post editor UIUI User interface and behavior closely. 

Preferences 

The preferences have been unified between the post and site editor. For instance, if a user enables the top toolbar in the post editor, it will be honored in the site editor and vice versa. 

This means that the following preferences have been moved from the core/edit-post or core/edit-site scopes into the core scope.

  • allowRightClickOverrides
  • distractionFree
  • editorMode
  • fixedToolbar
  • focusMode
  • hiddenBlockTypes
  • inactivePanels
  • keepCaretInsideBlock
  • mostUsedBlocks
  • openPanels
  • showBlockBreadcrumbs
  • showIconLabels
  • showListViewByDefault

Accessing the preferences using the previous scope will continue to work but it’s deprecated, you can now access and modify these preferences using:

const isFixedToolbar = window.wp.data.select( 'core/preferences' ).get( 'core', 'fixedToolbar' );
window.wp.data.dispatch( 'core/preferences' ).get( 'core', 'fixedToolbar', true );

Actions and selectors

For the same reasons, the following selectors and actions from ‘edit-post’ store to the ‘editor’ store:

  • setIsInserterOpened
  • setIsListViewOpened
  • isInserterOpened
  • isListViewOpened
  • isEditorPanelEnabled
  • isEditorPanelOpened
  • isEditorPanelRemoved
  • removeEditorPanel
  • toggleEditorPanelEnabled
  • toggleEditorPanelOpened
const isInserterOpened = window.wp.data.select( 'core/editor' ).isInserterOpened();

Editor Store

The site editor now relies on the editor package, thie means that in order to retrieve the currently edited post or entity, you can use the editor store selectors:

const editedPostType = wp.data.select( 'core/editor' ).getCurrentPostType();
const editedPostId = wp.data.select( 'core/editor' ).getCurrentPostId();

The rest of the editor store selectors and actions should also be now usable within the site editor.

Props to @audrasjb for the technical review and @leonnugraha for the copy review

#6-5, #dev-notes, #dev-notes-6-5

Updates to the HTML API in 6.5

WordPress 6.5 brings significant updates to the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. 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.. Notably, the Tag Processor received a major overhaul allowing it to scan every token in an HTML document and unlocking a broad array of new functionality. The HTML Processor supports much more of the HTML specification than it did when it was minimally introduced in WordPress 6.4.

New functionality in the Tag Processor.

The Tag Processor was designed to scan every tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) in an HTML document, skipping all of the non-tag tokens. In WordPress 6.5 it can scan everything. Tokens are the fundamental pieces that make up a document; in the case of HTML, they are the tags, comments, doctype definitions, and text nodes. This means that it’s now possible to read the text content of an HTML document, trivializing previously-complicated operations like stripping tags or truncating HTML.

Supporting this work is the introduction of a new concept called modifiable text. Modifiable text represents content within token boundaries, or content which can be changed without affecting the structure of the document as a whole. Different tokens contain different types of modifiable text:

  • The entire span of a text node is modifiable text.
  • The inside contents of an HTML comment is modifiable text.
  • The content between the opening and closing tags of special elements is modifiable content.

In this case, special elements refer to elements whose inner contents cannot contain other HTML tags. These include the contents of SCRIPT and STYLE elements as well as the contents of the TITLE and TEXTAREA elements. There are a few more representing deprecated or invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid. syntax: see the class documentation for a comprehensive list.

New Methods.

  • next_token() advances to the next token in the document, including closing tags. Unlike next_tag() there is no query for this method. It scans everything.
  • get_token_type() indicates what kind of token was found, e.g. a #tag or #text or #comment.
  • get_token_name() returns a value roughly corresponding to the DOM nodeName, e.g. SPAN or #text or html (for doctype declarations).
  • get_modifiable_text() returns the properly-decoded text content for a matched token.
  • get_comment_type() indicates why the token is a comment, since different kinds of invalid markup become HTML comments. For example, <​![CDA​TA[​text]​]> is an HTML comment of the type COMMENT_AS_CDATA_LOOKALIKE because it appears as though it was intended to be a CDATA section, which doesn’t exist within HTML content.
  • paused_at_incomplete_token() indicates if the Tag Processor reached the end of the document in the middle of a token. For example, it may have been truncated in the middle of a tag.

Example usage:

$title = null;
$text_content = '';
$processor = new WP_HTML_Tag_Processor( $html );
while ( $processor->next_token() ) {
    if ( '#text' === $processor->get_token_type() ) {
        $text_content .= $processor->get_modifiable_text();
    } elseif ( null === $title && 'TITLE' === $processor->get_token_name() ) {
        $title = $processor->get_modifiable_text();
    }
}

echo $title ? $title : '(untitled post)';
echo "\n\n";
echo $text_content;

Expanded support in the HTML Processor.

WordPress is now able to recognize and properly parse most HTML. There are only a few major exceptions.

  • The HTML Processor will bail any time it encounters a FORM, MATH, SVG, TABLE, or TEMPLATE tag. These elements introduce complicated parsing rules that require additional care, testing, and design work.
  • There are times when an HTML parser needs to implicitly create an element that wasn’t in the HTML itself, or when it needs to move a tag to an earlier place in the document. This requires further design work to properly communicate that the document has retroactively changed.
  • If the HTML Processor is fed full HTML documents or snippets that exist outside of a BODY element (e.g. a document HEAD), then it will abort, as it currently only supports parsing HTML inside a BODY context.

The last point highlights that the HTML Processor has been developed following the needs of 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.-related code and focused on rules in the HTML specification relating to how tags ought to be interpreted inside a BODY element. Once this section is complete, the others will be added. Thankfully, this is the hardest section by a long shot, and parsing full documents should follow quickly after the primary work is done.

Notes for experimenters.

If you’ve been experimenting with the HTML API and building custom subclasses of the Tag Processor then it’s important to understand two changes: handling of incomplete documents, and special HTML tags with modifiable text.

Incomplete documents.

Previously, when the Tag Processor reached the end of a document and there was an incomplete token (for instance, “<div cl“), it would return false and finish parsing the document. Now that the Tag Processor can scan and visit every token in the document, however, it will indicate if it encountered such a situation. When it does, it will still return false, but it will back up to the beginning of the token and freeze. In a future release, it will be possible to extend the document and continue processing. For now, if paused_at_incomplete_token() returns true, then you can know that there might have been more to the original HTML that was sent into the processor than it received.

Special HTML tags with modifiable text.

The HTML Processor properly tracks document structure and is the appropriate method for determining when an element starts and ends. Many simpler approaches will often seem correct enough for practical use, but these will all break down in common situations. While the Tag Processor makes it easier to estimate structure than regex-based approaches, be cautioned whenever skipping the rules that the HTML Processor implements, as even normative HTML often breaks simple mental models for translating HTML text into DOM structure.

For those who are relying on the Tag Processor to estimate structure, there’s a change in behavior that might break your subclasses: the Tag Processor no longer visits the closing tag for the group of special elements. These are tags like SCRIPT, STYLE, and TITLE. The reason for this change is that these elements cannot contain other tags inside of them. It will often look like they do (for instance, with <title>an <img> is plain text</title>), but the inner content is parsed as text and not as HTML. This change prevents misinterpreting those inner contents as HTML tags.

When the Tag Processor encounters a SCRIPT tag or any of these special elements, it will continue parsing until it finds the associated closing tag and then the inner contents will be available as modifiable text. For algorithms tracking depth in a document, they will not only need to check if the tag is_void(), but also if it’s a special element since the closing tag will no longer be separately visited.

Note that it’s still possible to visit a closing tag for a special element, but only if they are unexpected and come without a corresponding opening tag.


Follow along in the CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel #core-html-api or watch here for updated posts to be part of the conversation driving and developing this API.

Props to @stevenlinx for copy review on this post.

#dev-notes #dev-notes-6-5 #6-5

Script Modules in 6.5

A new “Script Modules” interface has been introduced to support native JavaScript modules in WordPress. 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/. modules use import and export and are often referred to as ECMAScript Modules or “ESM”.

This post will refer to “scripts” and “modules” for Scripts and Script Modules concepts, respectively.

JavaScript modules are a coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. web technology with a number of benefits like import and export for proper scoping, forced strict mode, and deferred loading. It’s important for WordPress to support modules and encourage their use as the future of JavaScript development.

Script Modules 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.

The interface is modeled after the existing scripts interface and should feel familiar. Modules are identified by a unique identifier (ID), analogous to a script handle.

The registered module ID should be identical to the imported module name in JavaScript. For example, the @wordpress/interactivity module can be used in another module as:

import * as interactivity from '@wordpress/interactivity';

Registered modules have an array of module dependencies. Dependencies can be a simple string (the dependency module ID) or an associative array of the following form:

$dependencies = array(
'id' => '@wordpress/interactivity',
'import' => 'dynamic' // Optional.
);

The array form optionally includes an import key with the value 'static' (default) or 'dynamic'. Dependencies that may not be needed or should only be loaded under some circumstances should use 'import' => 'dynamic'.

Note that these dependencies are module dependencies, not script dependencies. Script handles should not be listed as module dependencies.

The following functions are the most relevant parts of the interface for developers working with modules:

  • wp_register_script_module( string $id, string $src, array $deps = array(), $version = false ): Registers the module.
  • wp_enqueue_script_module( string $id, string $src = '', array $deps = array(), $version = false ): Marks the module to be enqueued. An optional $src argument can be provided to enqueue and register the module.
  • wp_deregister_script_module( string $id ): Deregisters the module.
  • wp_dequeue_script_module( string $id ): Unmarks the module so it is not enqueued.

Important notes

It’s strongly recommended that developers currently utilizing JavaScript modules in their extensions migrate to the Script Modules API. This will standardize behavior, bring a number of benefits, and prevent some of the following potential issues:

  • Any code that is currently using import maps may run into compatibility issues because multiple import maps are not currently supported.
  • If a module appears before an import map, an error will be triggered that causes the import map to be ignored. This would break some critical functionality that the Script Modules API relies on.

It’s important to migrate to the new API to prevent these issues. If it’s unfeasible to migrate, moving modules script to the footer may mitigate some of the potential issues.

Available modules

Two core modules are provided with 6.5.

@wordpress/interactivity is the interface for building interactive frontends with the Interactivity API.

@wordpress/interactivity-router defines an Interactivity API store with the core/router namespace, exposing relevant state and actions for client-side navigation.

There are no other core modules available at this time. The JavaScript packages available as scripts before 6.5 are not available as modules. For example, the @wordpress/api-fetch package corresponds to the wp-api-fetch script and is not available in WordPress as a module.

Working with Script Modules

The most relevant functions for working with modules are wp_register_script_module to register and wp_enqueue_script_module to enqueue modules. For example:

// Registers a module, it can now appear as a dependency or be enqueued.
wp_register_script_module(
'@my-plugin/shared',
plugin_dir_url( __FILE__ ) . 'shared.js'
);

// Registers and enqueues a module.
wp_enqueue_script_module(
'@my-plugin/entry',
plugin_dir_url( __FILE__ ) . 'entry.js',
array( '@my-plugin/shared' )
);

// Enqueues a previously registered module.
wp_enqueue_script_module( '@my-plugin/a-registered-module' );

In this example, the @my-plugin/shared module will be available to the @my-plugin/entry module:

// "@my-plugin/entry" module at …/entry.js
import * as shared from '@my-plugin/shared';
shared.doSomethingInteresting();

Blocks

WordPress 6.5 introduces a new viewScriptModule block metadata field that will handle module registration and enqueue automatically analogous to viewScript. A full dev note about viewScriptModule can be read here.

Module registration

Developers familiar with modern JavaScript development will recognize the module system and may wonder, “Do I have to register all my modules with WordPress in order to use them?” The short answer is no, but the recommended approach is to register all the modules.

JavaScript modules can import be imported by URLs. It’s common to see imports like import { utility } from './utilities.js' in modern applications. Because the Script Modules API is built on top of native JavaScript modules, it’s possible for modules to import relative paths in WordPress. However, the recommended approach is to register modules and use the registered ID to import the module. This has a few benefits:

  • Registered modules are available globally. There’s no need to worry about the module URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org.
  • Registered modules have versions. The Script Modules API transparently handles associating a module ID with the correct URL and version.
  • Risk of module duplication is reduced. If a module is imported through different URLs, the browser may fetch and execute multiple copies of what is ostensibly the same module.
  • Dependencies that are imported statically will be preloaded when the module is enqueued. This allows the browser to fetch them in parallel.

Relative imports to unregistered modules may be useful for prototyping and exploration, but the best practice for production code is to register modules with the Script Modules API.

Limitations

Modules and scripts are not compatible at this time. Modules cannot depend on scripts and scripts cannot depend on modules. This means that modules cannot depend on scripts like wp-i18n, wp-api-fetch, etc.

There is a workaround to use scripts from modules. Script functionality is shared by adding variables to the window scope, for example wp-api-fetch can be accessed via window.wp.apiFetch. To use scripts from modules at this time, developers must:

  • Ensure that the script is enqueued: wp_enqueue_script( ‘wp-api-fetch’ )
  • Access the script through the global scope: const { apiFetch } = window.wp

There are a number of downsides to this workaround, but it can be an effective solution. Follow Core Trac ticket #60647 for work on script and module interoperability.

Compatibility

JavaScript modules have excellent support in most browsers today. In addition, the Script Modules API includes a polyfill for browsers with lacking or incomplete support to make the number of supported browsers even greater.

Technical details

A full explanation of how the Script Modules API works is beyond the scope of this note, but this section will provide a brief overview.

The Script Modules API will track registered and enqueued modules. For each enqueued module, a <script type="module"> tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) will be added to load and execute the module.

A <script type="importmap"> tag will be added. The import map tells the browser how to map module IDs to URLs so that when it sees an import for '@wordpress/interactivity', it knows that the module should be fetched from the URL /wp-includes/js/dist/interactivity.min.js?ver=xyz. The import map includes all the dependencies of all enqueued modules, and all the dependencies of those dependencies, etc. The import map will not include dependencies of all the registered modules, only those that may be required on the page as dependencies, and it will not include the enqueued modules unless they are in the dependency graph of other enqueued modules.

A <link rel="modulepreload"> will be added for all static dependencies. Static dependencies are all dependencies that are not defined as array( 'id' => '…', 'import' => 'dynamic' ). This is an optimization hint for browsers, read more about it here.

Relevant links

Props

#6-5, #dev-notes, #dev-notes-6-5

Block metadata viewScriptModule field in 6.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. 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. now recognizes the viewScriptModule field in block.json metadata. This provides an experience for script modules that’s analogous to what scripts and the viewScript field currently provide. The script module declared in viewScriptModule will be enqueued when a block is rendered for viewing on the frontend.

This new field is important so that developers can use script modules on the frontend. Scripts cannot depend on script modules, so script modules are necessary to use script modules like the Interactivity API (via the @wordpress/interactivity script module).

Read more: Block metadata viewScriptModule field in 6.5

This post assumes a basic understanding of the Script Modules API, read more about it here.

Getting started

You can generate a simple block 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 using the @wordpress/create-block-interactive-template package:

npx @wordpress/create-block --template @wordpress/create-block-interactive-template

This will generate an interactive block from a template that uses viewScriptModule.

Usage

Add a viewScriptModule field to the metadata in block.json that points to the script module.

Here’s what a simple plugin might look like:

myplugin/
├── build/
│ ├── block.json
│ ├── …snip…
│ ├── view.asset.php
│ └── view.js
└── plugin.php

The only code in the plugin.php file calls register_block_type for the block:

add_action( 'init', function() {
register_block_type( __DIR__ . '/build/block.json' );
} );

The relevant metadata in build/block.json includes viewScriptModule:

{
"…snip…": "…",
"viewScriptModule": "file:./view.js"
}

build/view.js is the script module that depends on @wordpress/interactivity:

import { getContext, store } from '@wordpress/interactivity';

store( 'myplugin/demo', {
increment() {
getContext().val += 1;
},
decrement() {
getContext().val -= 1;
},
} );

The module asset file build/view.asset.php declares the view script module’s dependency on @wordpress/interactivity:

<?php return array(
'dependencies' => array('@wordpress/interactivity'),
);

REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/.

A new field view_script_module_ids has been added to the Block Types REST API. The field is a list of the view script module IDs associated with a block type.

Tooling

The @wordpress/scripts package is the standard way of compiling 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/. assets for use in WordPress. Experimental functionality has been added to the build and start scripts to support compiling modules. It can be enabled using --experimental-modules on the command line, for example:

 wp-scripts build --experimental-modules

Script module compilation with @wordpress/scripts does not support using your own webpack file at this time.

The example plugin above was compiled using the experimental module build with @wordpress/scripts.

@wordpress/dependency-extraction-webpack-plugin has been updated to produce script module asset files. No special configuration is required. See the package documentation for details.

Relevant links

Props

#6-5, #dev-notes, #dev-notes-6-5

Updates to Block Hooks in 6.5

First introduced in WordPress 6.4, 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. HooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same. offer an extensibility mechanism for Block Themes that allows extenders to inject a dynamic block in a location specified by an “anchor” block and a relative position. (For example, before or after the Post Content block.)

WordPress 6.5 updates Block Hooks to make them more widely useful and includes some frequently requested new features.

New features

Modified layouts

Previously restricted to layouts – templates, template parts, and patterns – that didn’t have any user modifications, Block Hooks now also work with modified layouts. This works out of the box; extenders do not need to update their code to benefit from this. Block Hooks will continue to respect user customizations. If a user moves or deletes a hooked block in the Site Editor, the Block Hooks mechanism will not re-insert it, thus preserving the user’s express intentions.

Navigation block

Additionally, it is now possible to inject hooked blocks into the Navigation block. Previously, a hooked block could only be added before or after the Navigation block, but now it can also be added as its first or last child.

As a consequence, the hooked_block_types 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.’s $context argument can now also be a WP_Post object with its post type set to wp_navigation.

This means that a negative condition, such as if ( ! $context instanceof WP_Block_Template ), is no longer sufficient to conclude that $context is an array (i.e., a pattern). Instead, use an affirmative check, such as if ( is_array( $context ) ).

The following example adds a (hypothetical) Shopping Cart block as the Navigation block’s last child, after ensuring that the block isn’t already present elsewhere in the Navigation menuNavigation Menu A theme feature introduced with Version 3.0. WordPress includes an easy to use mechanism for giving various control options to get users to click from one place to another on a site.:

function add_shopping_cart_block_to_navigation_block( $hooked_block_types, $relative_position, $anchor_block_type, $context ) {
	// Is $context a Navigation menu?
	if ( ! $context instanceof WP_Post || 'wp_navigation' !== $context->post_type ) {
		return $hooked_block_types;
	}

	// Does the Navigation menu already contain the block?
	if ( str_contains( $context->post_content, '<!-- wp:my-ecommerce/shopping-cart' ) ) {
		return $hooked_block_types;
	}

	if ( 'last_child' === $relative_position && 'core/navigation' === $anchor_block_type ) {
		$hooked_block_types[] = 'my-ecommerce/shopping-cart';
	}
	return $hooked_block_types;
}
add_filter( 'hooked_block_types', 'add_shopping_cart_block_to_navigation_block', 10, 4 );

New filters

In order to offer more fine-grained control over hooked blocks, two new filters have been introduced: hooked_block and hooked_block_{$hooked_block_type}. Both share the following signature:

  • $parsed_hooked_block (array|null) – The hooked block, in parsed block array format, or null, indicating that a previous filter has suppressed the injection of the given block.
  • $hooked_block_type (string) – The hooked block type name.
  • $relative_position (string) – The relative position of the hooked block (can be one of before, after, first_child, or last_child).
  • $parsed_anchor_block (array) – The anchor block, in parsed block array format.
  • $context (WP_Block_Template|WP_Post|array) – The block template, template part, wp_navigation post type, or pattern that the anchor block belongs to.

One of the most frequently requested features for Block Hooks was the ability to set a hooked block’s attributes. While it is generally advised to choose default values for block attributes that work well when the block is used as a hooked block, it is now possible to set custom values for its attributes via these new filters.

In addition, the filters allow setting a hooked block’s inner blocks (and, by extension, wrapping it inside of another block), or suppressing the hooked block altogether (by returning null).

Finally, the filters are also given the anchor block instance as an argument, so it’s possible to, for example, set the hooked block’s attributes based on the anchor block’s:

function set_block_layout_attribute_based_on_adjacent_block( $hooked_block, $hooked_block_type, $relative_position, $anchor_block ) {
	// Has the hooked block been suppressed by a previous filter?
	if ( is_null( $hooked_block ) ) {
		return $hooked_block;
	}

	// Is the hooked block adjacent to the anchor block?
	if ( 'before' !== $relative_position && 'after' !== $relative_position ) {
		return $hooked_block;
	}

	// Does the anchor block have a layout attribute?
	if ( isset( $anchor_block['attrs']['layout'] ) ) {
		// Copy the anchor block's layout attribute to the hooked block.
		$hooked_block['attrs']['layout'] = $anchor_block['attrs']['layout'];
	}

	return $hooked_block;
}
add_filter( 'hooked_block_my/like-button', 'set_block_layout_attribute_based_on_adjacent_block', 10, 4 );

For more examples, refer to the snippets found in the description of the PR that introduced the new filters.

Plugins block inspector panel toggles

The toggles for each hooked block in the block inspector’s “Plugins” panel have been updated to fix a confusing behavior that would remove the toggle in certain cases after it was deactivated. Furthermore, toggles are now shown for blocks added by the hooked_block_types filter; note that due to technical limitations, this currently only works for layouts that have user modifications.

A screenshot showing a Navigation block selected in the Site Editor. The block contains 'News', 'About', and 'Logout' links, and a shopping cart icon.

The Block Inspector sidebar is open. It is showing the 'Plugins' panel with toggles for the hooked blocks: one for the Shopping Cart, and one for the Login/out link.

Under the hood

The major technical challenge to making Block Hooks work with modified layouts was to ensure they would continue respecting user customizations to a given layout. That is, when a block was persisted, moved, or deleted by the user in the Site Editor, it wouldn’t end up being re-inserted by the Block Hooks mechanism.

It turned out that this problem could be solved by essentially a “finer-grained” version of the same principle (i.e., modified vs. unmodified). This is achieved by storing information about hooked block types in an ignoredHookedBlocks array inside the global metadata attribute on the anchor block. Specifically, it works via the two following operations:

On write (i.e., persisting a modified layout to the database): All hooked block types that were present during the edit are persisted to their respective anchor block’s ignoredHookedBlocks arrays. (Note that this is regardless of the nature of the edit: It works the same both for when the hooked block is persisted and when it is removed.)

On read (i.e., rendering on the front end or loading into the Site Editor): The Block Hooks mechanism will now look for the presence of a given hooked block type inside its anchor block’s ignoredHookedBlocks array. If a hooked block’s type name is found in that array, it will be ignored (i.e., not injected).

See this Trac ticket for more information on how this solution was conceived.

For controlled inner blocks: For inner blocks that aren’t present inside the containing block but loaded separately at runtime, the same ignoredHookedBlocks array is stored, but in a new post metaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress. field _wp_ignored_hooked_blocks instead of in the containing block’s attributes. This is how hooked blocks work in the Navigation block with its external wp_navigation post.


With these new features in place and several important limitations lifted, Block Hooks can now be used across a large number of layouts, without paying heed to whether the user has modified a layout or not. Specialized filters allow you to fine-tune hooked blocks by setting their attributes and inner blocks while also taking information about the anchor block instance into account when doing so. This makes Block Hooks a more intuitive and powerful tool for extending Block Themes.

We’re looking forward to seeing what extenders will create with this 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.!

Props to @dmsnell, @gziolo, @ndiego, and @leonnugraha for peer review.

#dev-notes

Performance improvements for registering block variations with callbacks

Background

In WordPress 5.8, 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. for registering 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. variations was introduced, bringing new capabilities to developers. However, it soon became evident that generating these variations had a non-trivial performance cost, particularly when used for template-part and navigation-link in WordPress 5.9 and post-terms in WordPress 6.1.

The coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. of this issue was that these variations were being generated on every page load due to their registration using the init hook. This was inefficient, as the variations were only needed in the editor or for returning block data in the REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/.. This redundancy in loading led to unnecessary performance overhead, underscoring the need for a more streamlined approach.

What is changed

In WordPress 6.5, we’ve introduced $variation_callback as a new attribute in WP_Block_Type. This feature allows developers to register variation-building functions as callbacks rather than building variations before registration. With this approach, variations are constructed from this callback only when they are accessed for the first time. 

Consequently, the WP_Block_Type::get_variations() method was introduced as the primary means to access variations. This method skillfully checks for a callback in variation_callback and triggers the callback, but only during the first access of the variations. This efficient approach ensures that the callback is executed just once, optimizing performance by avoiding redundant processing on subsequent accesses. Additionally, this strategy aids in lazy loading, as variations no longer need to be loaded during registration.

Moreover, it integrates the get_block_type_variations 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., which provides a versatile mechanism for developers to modify the resulting variations. These enhancements reflect WordPress’s ongoing commitment to improving its developer-centric features and maintaining compatibility with existing functionalities.
In WordPress 6.5, a significant alteration is made to WP_Block_Type::$variations. The notable change involved transitioning the visibility of variations from public to private. This modification was specifically designed to necessitate the use of the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher magic __get method for accessing variations only via WP_Block_Type::get_variations().

Please note that the modifications to WP_Block_Type::$variations may introduce certain limitations that require developer attention. These are detailed in the “Developer Action” section below.

Lazy loading variations using variation_callback

To facilitate the lazy loading of variations, we can replace the traditional method of loading variations with a callback. This approach is exemplified in the case of GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ PR #56952, which is aimed at enhancing performance.

Previously, template-part variations were loaded as follows:

register_block_type_from_metadata(
    __DIR__ . '/template-part',
    array(
        'render_callback'    => 'render_block_core_template_part',
        'variations'         => build_template_part_block_variations(),
    )
);

To optimize this, we have transitioned to using a variation_callback:

register_block_type_from_metadata(
    __DIR__ . '/template-part',
    array(
        'render_callback'    => 'render_block_core_template_part',
        'variation_callback' => 'build_template_part_block_variations',
    )
);

It’s important to note that if both variations and variation_callback are defined, like in the following example:

register_block_type_from_metadata(
'block-name',
array(
'variations' => array( 'test-variation' => array( 'test-variations' ) ),
'variation_callback' => 'get_test_variations',
)
);

In this scenario, the variations array takes precedence, and the variation_callback will not be called.

Developer action required

With the addition of variations to the existing magic function framework in WP_Block_Type, a significant limitation emerges: the inability to modify variations by reference directly. This change impacts how variations were traditionally updated.

Consider these examples of updating variations by reference, which will no longer function as expected in WordPress 6.5:

$block_type->variations[] = array( 'test' => array( 'test' ) );
// or
$block_type->variations['example1'] = array( 'test' );

To overcome this limitation in WordPress 6.5, a workaround involving a temporary variable can be used. Here’s how you can modify the temporary variable and then reassign it back to $block_type->variations:

$variations = $block_type->variations;$variations[] = array( 'test' => array( 'test' ) );
$block_type->variations = $variations;
// Similarly$variations = $block_type->variations;
$variations['example1'] = array( 'test' );$block_type->variations = $variations;

Alternatively, to align with the latest updates and best practices in WordPress, you might consider using the get_block_type_variations filter (reference link).

Utilizing the get_block_type_variations filter for enhanced variation management

The introduction of the get_block_type_variations filter in WordPress 6.5 allows for the manipulation and customization of the variations array, providing greater flexibility in handling block variations.

Here’s an implementation example of the get_block_type_variations filter:

function modify_block_type_variations( $variations, $block_type ) {
// Example: Add a new variation
if ( 'block-name' === $block_type->name ) {
$variations[] = array(
'name' => 'new-variation',
'title' => __( 'New Variation', 'textdomain' ),
// Other variation properties...
);
}

return $variations;
}
add_filter( 'get_block_type_variations', 'modify_block_type_variations', 10, 2 );

In this example, the modify_block_type_variations function is hooked to the get_block_type_variations filter. It checks if the block type is ‘block-name‘ and then adds a new variation to the variations array. This function then returns the modified variations array.

By leveraging this filter, developers can dynamically adjust the variations according to specific requirements or conditions.

Please refer to #59969 for additional details on these changes.

Props to @adamsilverstein, @westonruter, @joemcgill, and @leonnugraha for reviewing this post.

#6-5, #block-api, #dev-notes, #dev-notes-6-5

Hallway Hangout: Let’s chat about WordPress Playground

With WordPress Playground gradually becoming a larger part of our day-to-day lives as developers, it’s time to chat about what the project should look like going forward. There is a proposal for a v2 of the Blueprints schema, and we could use your feedback on current and future use of Playground.

So let’s have a casual conversation on what would benefit you as developers.

How to join

If you’re interested in joining us, the Hallway Hangout will be on Monday, March 4, 2024 at 04:00 pm (16:00) UTC. A Zoom link will be shared in the #outreach Slack channel before the session starts. 

Everyone is welcome to join, regardless of whether it’s just to listen or actively participate. This session will be recorded and recapped here on the Make CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. blogblog (versus network, site).

As usual, Hallway Hangouts are conversational events where you, the WordPress community, can provide your feedback directly to contributors to WordPress. This feedback is invaluable in steering the direction of the overall project.

Agenda

On the whole, the biggest thing we want to accomplish with this event is to bring more awareness to the WordPress Playground project, which lets you experience WordPress directly from the browser (no complicated setup necessary). Give it a try →

With this goal in mind, @zieladam, the architect of Playground, and I would like to discuss:

  • The Playground Blueprints system and how it works
  • What existing features you find the most useful in your own work
  • What current features feel limiting
  • The missing features you’d like to see going forward

We hope that you all can join us and help shape the future of WordPress Playground.

Post reviewed by @zieladam.

#hallway-hangout, #outreach, #playground

Summary, Dev Chat, February 28, 2024

Start of the meeting in SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

Announcements

WordPress 6.5 Beta 3 was released on February 27, 2024. Thanks to everyone involved and who came to help test.

Forthcoming Releases

Major releasemajor release A release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope.: 6.5

WordPress 6.5 Release Candidaterelease candidate One of the final stages in the version release cycle, this version signals the potential to be a final release to the public. Also see alpha (beta). 1 is scheduled for next week (see release schedule). A call for testing for BetaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. 3 was posted earlier today. See: Help test WordPress 6.5 Beta 3.

During open floor, @marybaum asked for confirmation on roles for the release party for next week:

GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/: 17.8.0

Gutenberg 17.8.0 released earlier today. The What’s new in Gutenberg 17.8? (28 February) post was published following the meeting.

Discussions

With this being the last Dev Chat before WP 6.5 RC1, the discussion focused on issues related to the release. Specifically, the Font Library, and organizing release squads for 6.6 (and 6.5 minors).

Font Library

This discussion begins here.

@swissspidy noted that some concerns were raised about the upload location, capabilities, and use (or not use) of attachments for storing metadata.

Background conversation starting in Slack, and following on these GitHubGitHub GitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ issues (props @jorbin):

@youknowriad identified this as the next step:

I’d love if we can get an agreement on this https://github.com/WordPress/gutenberg/issues/59417 at this point it doesn’t seem like a consensus is possible, so I’m unsure how a decision like that is made.

The next step identified in the meeting is for the release tech leads (@davidbaumwald, @swissspidy, @get_dave, and @youknowriad) to make a decision about the next steps for this feature’s inclusion in this release based on the input that has already been given on the relevant tickets.

Organizing release squads for upcoming releases

As we’re nearing the end of the 6.5 release cycle, it’s a good time to start getting squads in place for the 6.6 and 6.5.x releases.

A previous Call for Volunteers was made, which included all three major release for the year. @marybaum volunteered to follow up an help wrangle a followup effort for the 6.6 release cycle.

@jorbin agreed to help identify folks who could help with release responsibilities for 6.5 minor releases, since he’s helped lead the minor releases during the 6.4 cycle.

Highlighted posts

The full list of posts from the last week in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. can be read on the agenda at this link.

Open floor

See the previous note in Future Releases section about coordinating roles for the RC1 release, that was raised during open floor.

@poena pointed out that we did not discuss one topic on the agenda: “Should we reduce the number of leads?”. @joemcgill agreed to include this discussion in a future meeting agenda.

Following the meeting, @costdev asked for feedback on #60504. Mainly: Whether this is a blockerblocker A bug which is so severe that it blocks a release. and if so, how can we unblock it for the long term?

Props to @mikachan for reviewing.

#6-5, #dev-chat, #summary

WordCamp Asia 2024 Contributor Day Core and Core Editor tables

It’s that time of year again! Whether you’re joining Contributor DayContributor Day Contributor Days are standalone days, frequently held before or after WordCamps but they can also happen at any time. They are events where people get together to work on various areas of https://make.wordpress.org/ There are many teams that people can participate in, each with a different focus. https://2017.us.wordcamp.org/contributor-day/ https://make.wordpress.org/support/handbook/getting-started/getting-started-at-a-contributor-day/. in person in Taipei or following along online via the #contributor-day SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel, thank you and welcome!

In order to ensure that everything goes seamlessly on the day, you should consider installing a local development environment on your laptop beforehand. Conference venue wifi isn’t always the best, especially when there are many folks using it at once, and this prerequisite is much easier to accomplish over a stable, fast connection.

To start with, at a minimum, you’ll need to have the latest stable version of nodejs and npm, which you can find here: https://nodejs.org/en (LTS is the one CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. and GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ use) and Git installed locally (for core you can also use SVNSVN Subversion, the popular version control system (VCS) by the Apache project, used by WordPress to manage changes to its codebase.).

Depending on whether you’re planning to work on Core or Gutenberg, there are a few different options:

For Core, clone the repo and follow the instructions here to install the included development environment. Docker is a prerequisite for it, so if you pick this option, go ahead and install Docker first.

For the editor, clone the Gutenberg repo and you can then use the wp-env package, which also requires Docker.

Note that if you want to install both these environments simultaneously, the port that the core one runs on will conflictconflict A conflict occurs when a patch changes code that was modified after the patch was created. These patches are considered stale, and will require a refresh of the changes before it can be applied, or the conflicts will need to be resolved. with the Gutenberg test environment. The easiest workaround for this is to change the core port, either by editing the config file locally or setting it in the terminal before starting up the environment.

An alternative to these is wp-now, which is a more lightweight option that requires only node/npm. It’s based on wp-playground. Note that there have been issues with playground on Windows.

For those attending in person, we’ll be located in the Code Lounge (South Lounge) on the third floor.

It’s also required to create a WordPress.org account if you don’t already have one, and if you’re using GitGit Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance. Most modern plugin and theme development is being done with this version control system. https://git-scm.com/., you’ll also need a GitHub.com account.

See you there, or online!

Thanks to @kirasong for reviewing and suggesting changes.

#contributor-day-2, #wordcamp