REST API Changes in WordPress 5.8

The following is a snapshot of some of the changes to 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/. in WordPress 5.8. For more details, see the full list of closed tickets.

Widgets

WordPress 5.8 sees the introduction of a 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.-based widgets editor and with it the creation of several REST API endpoints dedicated to widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. management. Before diving in to how the new endpoints operate, I’d like to provide some background about how widgets work that should make the following sections more clear.

Instance Widgets

The predominant way to create widgets is to subclass the WP_Widget base class and register the widget with register_widget. These are referred to as “multi” widgets. These widgets have multiple instances that are identified by their number, an incrementing integer for each widget type.

Each instance has its own setting values. These are stored and fetched by WP_Widget which allows for the REST API to include these values. However, since a widget’s instance can contain arbitrary data, for example a DateTime object, the REST API cannot always serialize a widget to JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.. As such, a widget’s data is always serialized using the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher serialize function and then base64 encoded. This data is also exposed with a hash value which is a wp_hash signature of this value to prevent clients from sending arbitrary data to be deserialized with unserialize.

For widgets that can be safely accept and expose their instance data as JSON, pass the show_instance_in_rest flag in the $widget_options parameter.

class ExampleWidget extends WP_Widget {
    ...
    /**
     * Sets up the widget
     */
    public function __construct() {
        $widget_ops = array(
            // ...other options here
            'show_instance_in_rest' => true,
            // ...other options here
        );
        parent::__construct( 'example_widget', 'ExampleWidget', $widget_ops );
    }
    ...
}

Reference Widgets

Far less common, but still supported, are widgets that are registered using wp_register_sidebar_widget and wp_register_widget_control directly. These are referred to as “reference”, “function-based”, or “non-multi” widgets. These widgets can store their data in an arbitrary location. As such, their instance values are never included in the REST API.

Widget Types

Accessible via /wp/v2/widget-types, the widget types endpoint describes the different widget types that are registered on the server. The endpoint is accessible to users who have permission to edit_theme_options. By default, this is limited to Administrator users.

Response Format

{
  "id": "pages",
  "name": "Pages",
  "description": "A list of your site’s Pages.",
  "is_multi": true,
  "classname": "widget_pages",
  "_links": {
    "collection": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/widget-types"
      }
    ],
    "self": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/widget-types/pages"
      }
    ]
  }
}

Encode Endpoint

Multi widgets have access to the /wp/v2/widget-types/<widget>/encode endpoint. This endpoint is used to convert htmlHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. form data for the widget to the next instance for the widget, render the widget form, and render the widget preview.

For example, let’s say we want to interact with the 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. widget. First, we’ll want to request the widget form from the server.

POST /wp/v2/widget-types/meta/encode
{
  "instance": {},
  "number": 1
}

For now, let’s assume we’re working with a new widget. The instance is empty because this is a new widget, so we’ll be rendering an empty form. The number argument can be omitted, but including one is recommended to provide stable input ids. You’ll receive a response similar to this. The widget preview has been snipped for brevity.

{
  "form": "<p><label for=\"widget-meta-1-title\">Title:</label><input class=\"widefat\" id=\"widget-meta-1-title\" name=\"widget-meta[1][title]\" type=\"text\" value=\"\" /></p>",
  "preview": "<div class=\"widget widget_meta\">...</div>",
  "instance": {
    "encoded": "YToxOntzOjU6InRpdGxlIjtzOjA6IiI7fQ==",
    "hash": "77e9f20acb54fa4f77de5a865333c0e6",
    "raw": {
      "title": ""
    }
  }
}

The provided form can then be rendered and edited by the user. When you want to render a new preview or are ready to begin saving, call the encode endpoint again with the url encoded form data and the instance value returned from the first response.

POST /wp/v2/widget-types/meta/encode
{
  "instance": {
    "encoded": "YToxOntzOjU6InRpdGxlIjtzOjA6IiI7fQ==",
    "hash": "77e9f20acb54fa4f77de5a865333c0e6",
    "raw": {
      "title": ""
    }
  },
  "number": 1,
  "form_data": "widget-meta%5B1%5D%5Btitle%5D=Site+Info"
}

The REST API will call the widget’s update function to calculate the new instance based on the provided form data. The instance object can then be used to save a widget via the widgets endpoint.

{
  "form": "<p><label for=\"widget-meta-1-title\">Title:</label><input class=\"widefat\" id=\"widget-meta-1-title\" name=\"widget-meta[1][title]\" type=\"text\" value=\"Site Info\" /></p>",
  "preview": "<div class=\"widget widget_meta\">...</div>",
  "instance": {
    "encoded": "YToxOntzOjU6InRpdGxlIjtzOjk6IlNpdGUgSW5mbyI7fQ==",
    "hash": "0e9a5bff2d28cba322c8cd27cd4e77af",
    "raw": {
      "title": "Site Info"
    }
  }
}

Widgets Endpoint

The widgets endpoint is used for performing CRUDCRUD Create, read, update and delete, the four basic functions of storing data. (More on Wikipedia.) operations on the saved widgets. Like the widget types endpoint, the widgets endpoints required the edit_theme_options capability to access.

To retrieve widgets, make a GET request to the /wp/v2/widgets endpoint. The sidebar parameter can be used to limit the response to widgets belonging to the requested sidebarSidebar A sidebar in WordPress is referred to a widget-ready area used by WordPress themes to display information that is not a part of the main content. It is not always a vertical column on the side. It can be a horizontal rectangle below or above the content area, footer, header, or any where in the theme..

To create a widget, for instance the widget from our previous example, make a POST request to the /wp/v2/widgets endpoint. The instance is the same value returned from the encode endpoint. The id_base is the unique identifier for the widget type and sidebar is the id of the sidebar to assign the widget to. Both are required.

POST /wp/v2/widgets
{
	"instance": {
		"encoded": "YToxOntzOjU6InRpdGxlIjtzOjk6IlNpdGUgSW5mbyI7fQ==",
		"hash": "0e9a5bff2d28cba322c8cd27cd4e77af",
		"raw": {
			"title": "Site Info"
		}
	},
	"sidebar": "sidebar-1",
	"id_base": "meta"
}

The endpoint will return information about the newly created widget.

{
  "id": "meta-1",
  "id_base": "meta",
  "sidebar": "sidebar-1",
  "rendered": "<div class=\"widget widget_meta\">...</div>",
  "rendered_form": "<p><label for=\"widget-meta-1-title\">Title:</label><input class=\"widefat\" id=\"widget-meta-1-title\" name=\"widget-meta[1][title]\" type=\"text\" value=\"Site Info\" /></p>",
  "instance": {
    "encoded": "YToxOntzOjU6InRpdGxlIjtzOjk6IlNpdGUgTWV0YSI7fQ==",
    "hash": "dac44c3ebfa0428fed61829fa151e4e8",
    "raw": {
      "title": "Site Info"
    }
  },
  "_links": {
    "self": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/widgets/meta-1"
      }
    ],
    "collection": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/widgets"
      }
    ],
    "about": [
      {
        "embeddable": true,
        "href": "https://trunk.test/wp-json/wp/v2/widget-types/meta"
      }
    ],
    "wp:sidebar": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/sidebars/sidebar-1/"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

Since the meta widget (and all other built-in widgets) is registered with show_instance_in_rest enabled you could bypass the encode endpoint and use instance.raw instead. For example, if we wanted to update the widget to have a new title, we could make the following PUT request to /wp/v2/widgets/meta-1.

PUT /wp/v2/widgets/meta-1
{
	"instance": {
		"raw": {
			"title": "Site Meta"
		}
	}
}

A PUT request can also be made to update the sidebar assigned to a widget by passing a new sidebar id in the request.

To delete a widget, send a DELETE request to the individual widget route. By default, deleting a widget will move a widget to the Inactive Widgets area. To permanently delete a widget, use the force parameter. For example: DELETE /wp/v2/widgets/meta-1?force=true.

Sidebars Endpoints

Found under /wp/v2/sidebars, the sidebars endpoint is used to manage a site’s registered sidebars (widget areas) and their assigned widgets. For example, the following is the response for the first footer area in the Twenty Twenty theme.

{
  "id": "sidebar-1",
  "name": "Footer #1",
  "description": "Widgets in this area will be displayed in the first column in the footer.",
  "class": "",
  "before_widget": "<div class=\"widget %2$s\"><div class=\"widget-content\">",
  "after_widget": "</div></div>",
  "before_title": "<h2 class=\"widget-title subheading heading-size-3\">",
  "after_title": "</h2>",
  "status": "active",
  "widgets": [
    "recent-posts-2",
    "recent-comments-2",
    "meta-1"
  ],
  "_links": {
    "collection": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/sidebars"
      }
    ],
    "self": [
      {
        "href": "https://trunk.test/wp-json/wp/v2/sidebars/sidebar-1"
      }
    ],
    "wp:widget": [
      {
        "embeddable": true,
        "href": "https://trunk.test/wp-json/wp/v2/widgets?sidebar=sidebar-1"
      }
    ],
    "curies": [
      {
        "name": "wp",
        "href": "https://api.w.org/{rel}",
        "templated": true
      }
    ]
  }
}

The widgets property contains an ordered list of widget ids. While all other properties are readonly, the widgets property can be used to reorder a sidebar’s assigned widgets. Any widget ids omitted when updating the sidebar will be assigned to the Inactive Widgets sidebar area.

For example, making a PUT request to /wp/v2/sidebars/sidebar-1 with the following body will remove the Recent Comments widget, and move the Meta widget to the top of the sidebar.

PUT /wp/v2/sidebars/sidebar-1
{
  "widgets": [
    "meta-1",
    "recent-posts-2"
  ]
}

For more information about the changes to widgets in 5.8, check out the Block-based Widgets Editor dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase..

Additional Changes

Posts Collection Tax Query Accepts operator

By default, a post must contain at least one of the requested terms to be included in the response. As of [51026], the REST API accepts a new operator property that can be set to AND to require a post to contain all of the requested terms.

For example, /wp/v2/posts?tags[terms]=1,2,3&tags[operator]=AND will return posts that have tags with the ids of 1, 2, and 3.

See #41287 for more details.

Props to @noisysocks for reviewing.

#5-8, #dev-notes, #rest-api

Block-based Widgets Editor in WordPress 5.8

WordPress 5.8 introduces a 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.-based widgets editor to the Widgets screen (Appearance → Widgets) and CustomizerCustomizer Tool built into WordPress core that hooks into most modern themes. You can use it to preview and modify many of your site’s appearance settings. (Appearance → Customize → Widgets). The new editor allows users to add blocks to their widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. areas using the familiar block editor interface introduced in WordPress 5.0. This gives users powerful new ways to customise their sites using the rich library of coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. and third party blocks. Existing widgets and third party widgets will continue to work and can be used alongside blocks.

Opting out of the block-based widgets editor

The block-based widgets editor is enabled in WordPress 5.8 by default. There are several ways to restore the classic editor:

  • A theme author may include remove_theme_support( 'widgets-block-editor' ). Learn more.
  • A site administrator may use the new use_widgets_block_editor 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.. Learn more.
  • A user may install and activate the Classic Widgets plugin.

New Widgets screen

The widgets.php adminadmin (and super admin) screen (Appearance → Widgets) now loads a block-based widgets editor which exists in the @wordpress/edit-widgets package.

The editor is built using ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. and is similar to the editor used for posts and pages (@wordpress/edit-post) and uses many of the same subsystems: @wordpress/interface and @wordpress/components for UIUI User interface, @wordpress/block-editor for block editing, @wordpress/data and @wordpress/core-data for persisting changes, and so on.

A new filterable function, wp_use_widgets_block_editor(), is used by widgets.php to determine whether to load the new block-based editor or the classic editor.

The Widgets screen is extendable via block editor APIs such as registerPlugin, registerBlockType, registerBlockVariation, and so on.

The Widgets screen uses new 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/. endpoints which are detailed in a seperate dev note.

New Customizer control

The Widgets section in the Customizer (Appearance → Customize → Widgets) now loads a new control (WP_Sidebar_Block_Editor_Control) which contains an embedded block-based widgets editor that exists in the @wordpress/customize-widgets package.

The editor is built using React and uses @wordpress/block-editor and @wordpress/components to implement its block editing interface. It does not use @wordpress/data or @wordpress/core-data to persist changes. Instead, the existing Customizer JavaScript API is used.

A new filterable function, wp_use_widgets_block_editor(), is used by WP_Customize_Manager to determine whether or not to log the new block-based editor control or the classic editor control.

The block-based widgets editor in the Customizer is extendable via block editor APIs such as registerBlockType, registerBlockVariation, and so on.

New block: Legacy Widget

Existing widgets and third party widgets can be edited in the block-based widgets editor via the new Legacy Widget block. This block has an identifier of core/legacy-widget and exists in the @wordpress/widgets package. The Legacy Widget block is compatible with most third party widgets.

Broadly speaking, the Legacy Widget block has three states:

  1. Select. When first inserted, the block displays a list of widgets available to choose from. The list can be customised using the widget_types_to_hide_from_legacy_widget_block filter.
  2. Edit. When selected, the block displays the widget’s control form fields. This is determined by the widget’s WP_Widget::form() implementation.
  3. Preview. When not selected, the block displays a preview of how the widget will look once saved. This is determined by the widget’s WP_Widget::widget() implementation. A “No preview available.” message is automatically shown when widget() does not output any meaningful HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers.. Learn more.

The Legacy Widget block is not available in other block editors including the post editor, though this can be enabled for advanced use cases.

New widget: Block

Blocks added to widget areas are persisted using the same widget storage mechanism added in WordPress 2.8. Under the hood, each block is serialised into HTML and stored in a block widget. This is represented by a new WP_Widget_Block subclass that extends WP_Widget. A block widget is a specialised case of the HTML widget and works very similarly.

If blocks are added to a widget area, and then the block-based widgets editor is disabled, the blocks will remain visible on the frontend and in the classic widgets screen.

Tips to prepare for the new block-based widgets editor

Use the widget-added event to bind event handlers

The Legacy Widget block will display a widget’s control form in a way that is very similar to the Customizer and is therefore compatible with most third party widgets. Care must be taken, however, to always initialise event handlers when the widget-added jQuery event is triggered on document.

( function ( $ ) {
    $( document ).on( 'widget-added', function ( $event, $control ) {
        $control.find( '.change-password' ).on( 'change', function () {
            var isChecked = $( this ).prop( 'checked' );
            $control.find( '.password' ).toggleClass( 'hidden', ! isChecked );
        } );
    } );
} )( jQuery );

Use block_categories_all instead of block_categories

The block_categories filter has been deprecated and will only be called in the post and page block editor. 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 developers that wish to support the widgets block editor should use the new block_categories_all filter which is called in all editors. See #52920 for more details.

Allow migrating from widgets to blocks

Many core and third party widgets have a functionally equivalent block. For example, core’s Recent Posts widget is analogous to core’s Latest Posts block.

In order to avoid duplicate functionality, is is recommended that plugin authors provide a way for users to convert their existing widgets to any equivalent block. WordPress 5.8 provides a mechanism for doing this using block transforms:

  1. Configure your widget to display its instance in the REST API by setting show_instance_in_rest to true in $widget_options.
  2. Add a block transform to your block from the core/legacy-widget block.
  3. Hide your widget from the Legacy Widget block using the widget_types_to_hide_from_legacy_widget_block filter.

There is a guide containing more detailed instructions in the Block Editor Handbook.

Don’t use @wordpress/editor

Many legacy widgets call the wp.editor.initialize() 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/. function to instantiate a TinyMCE editor. If a plugin or block uses the @wordpress/editor package and enqueues wp-editor as a script dependency, this will re-define the wp.editor global, often resulting in a wp.editor.initialize is undefined error.

Don’t use functions like is_admin() that won’t work in a REST API request

Because the Legacy Widget block makes REST API requests in order to render widgets, admin-only functions like is_admin() and is_plugin_available() are not available.


Written by @andraganescu and @noisysocks.
Thanks to @talldanwp, @isabel_brison, @kevin940726, and @get_dave for reviewing.

#5-8 #dev-notes #feature-widgets-block-editor #widgets #block-editor

Miscellaneous developer focused changes in WordPress 5.8


Update on July 1, 2021: Added new 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. info in RevisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. section. – @milana_cap


WordPress 5.8 brings a lot of smaller changes that developers should know about. Here’s a breakdown.

Build/Test Tools: Remove IE11 from the list of supported browsers

In WordPress 5.8, phase one of the dropping support for IE11 plan will take place. When considering three different data points, IE11 usage has fallen below a 1% average. After a discussion and debate, the decision was made to remove support for IE 11. In addition to opening the door for using more modern APIs, this will result in smaller script files, lower maintenance burden, and decreased build times.

The wp-polyfill script is responsible for ensuring all newer features function in the older browsers supported by WordPress. In past releases, this script was a copy of the file distributed in the @babel/polyfill package, which among other things, included regenerator-runtime.

This package was deprecated and has been replaced with the core-js package in the build process. core-js allows the polyfill file to be built dynamically, but no longer includes the regenerator-runtime script.

The regenerator-runtime script handle has been added to WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., and has been added as a dependency to wp-polyfill in order to be backwards compatible with any 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 or theme registering wp-polyfill as a script dependency expecting regenerator-runtime to be present.

It is recommended that developers add the regenerator-runtime script as a dependency to any script that requires it. In future releases, removing regenerator-runtime as a dependency of wp-polyfill will be considered.

There are several other polyfill scripts included in WordPress for the sole purpose of IE11 support. They will continue to be included, but will no longer be loaded by default. They are:

  • wp-polyfill-dom-rect
  • wp-polyfill-element-closest
  • wp-polyfill-fetch
  • wp-polyfill-formdata
  • wp-polyfill-node-contains
  • wp-polyfill-object-fit
  • wp-polyfill-url

For more information, see #52941, #53077, and #53078.

Formatting: More consistency and control over wp_get_document_title()

In wp_get_document_title(), the returned value is currently passed directly through wptexturize(), convert_chars(), and capital_P_dangit(), and is done so after the document_title_parts filter is run.

This makes it impossible to fully control the output of wp_get_document_title() and is inconsistent with how other similar text is processed with these functions.

The new document_title filter, which is run immediately before returning the results of the wp_get_document_title() function, moves the three formatting functions mentioned above to the new filter hook. This allows developers to further modify the title after being prepared by WordPress, or to modify the functions hooked to this filter as they wish.

For more information, see #51643.

General: Consistent type for integer properties of WP_Post, WP_Term, WP_User and a bookmark object

Some properties of the WP_PostWP_Term, and WP_User classes are documented as integers, so it should be a safe assumption to always treat them as such. However, that is not the case when get_post() or get_term() is called with an editattribute, or js context, because all values are run through esc_attr() or esc_js() in that case, and these properties are unexpectedly converted to strings.

This applies to the following functions:

  • sanitize_post_field()
  • sanitize_term_field()
  • sanitize_user_field()
  • sanitize_bookmark_field()

and the following properties:

  • WP_Post::ID
  • WP_Post::post_parent
  • WP_Post::menu_order
  • WP_Term::term_id
  • WP_Term::term_taxonomy_id
  • WP_Term::parent
  • WP_Term::count
  • WP_Term::term_group
  • WP_User::ID
  • $bookmark::link_id
  • $bookmark::link_rating

As WordPress moves towards strict type comparisons (see #52627 or #52482) it is important to make the type of these properties consistent in all contexts, so that using strict comparison does not cause unexpected issues.

In WordPress 5.8, these functions and properties will now reliably return an be set to integer values.

For more information, see #53235.

Posts/Post Types: Use _prime_post_caches() for speeding up cached get_pages() call

The get_pages() function uses a cache containing the ID of pages matching parameters of a previous call.

The IDs are, on a subsequent call with the same parameters, inflated using the get_post() function call. This works well in terms of the same request, as all the pages were previously added to the in-memory cache.

However, on a subsequent request, when the cache is hit, there are likely no pages already in the in-memory cache, and those need to be fetched from the backend cache server, one by one.

By taking advantage of wp_cache_get_multiple() instead of fetching each individual page from the backend cache server one by one, sites with persistent cache backend will have improved speed, but also sites without a persistent cache backend will benefit from the bulk SQL query constructed by the _prime_post_caches() function.

The performance gains should be most noticeable in case a site has a lot of pages which are being requested via get_pages() function.

For more information, see #51469.

Users: Pass $userdata to the actions and filters in wp_insert_user()

There are several action and filter 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. within wp_insert_user() that would benefit from being able to access the raw $userdata array passed into the function. One use case where this would be useful is extending the wp user import-csv command in WP-CLIWP-CLI WP-CLI is the Command Line Interface for WordPress, used to do administrative and development tasks in a programmatic way. The project page is http://wp-cli.org/ https://make.wordpress.org/cli/. This command is a wrapper for wp_insert_user() but it’s not possible to provide custom user 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. fields.

Here are the hooks gaining a new parameter:

  • wp_pre_insert_user_data (filter)
  • insert_user_meta (filter)
  • profile_update (action)
  • user_register (action)

This will allow hooked functions to perform more contextual adjustments to new users, and makes supplying custom user meta fields possible.

For more information, see #53110.

Media: Introduce image_editor_output_format filter

As detailed in a previously published dev note, WordPress 5.8 now supports the WebP image format.

WebP is a modern image format that provides improved lossless and lossy compression for images on the web. WebP images are around 30% smaller on average than their JPEG or PNG equivalents, resulting in sites that are faster and use less bandwidth. WebP is supported in all modern browsers according to caniuse.

WordPress 5.8 adds WebP support by @adamsilverstein

When images are uploaded, WordPress generates smaller sub sizes as defined using add_image_size(). By default, WordPress will generate these sub sizes in the same format as the original. Because of the performance benefits of the WebP format, it may be desirable for sub sizes to be generated in WebP instead of the original format.

In WordPress 5.8, the new image_editor_output_format filter hook can be used to change the file format used for image sub sizes. This can be used to switch all sub sizes to WebP, or any other desired format (JPEG, etc.).

The following example shows how to generate all sub sizes for JPG images using WebP:

<?php
function mysite_wp_image_editor_output_format( $formats ) {
	$formats['image/jpg'] = 'image/webp';

	return $formats;
}
add_filter( 'image_editor_output_format', 'mysite_wp_image_editor_output_format' );

Note: both the GD and ImageMagick libraries support the WebP format in both lossy and lossless. However, only ImageMagick supports animated images.

Setting the output format to WebP will verify if the web server supports it, and if not it will not change the format, i.e. won’t work.

For more information, see #52867.

General: Pass the scheme to all the *_url filters

A new parameter representing the URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org $scheme has been added to admin_url, includes_url, network_admin_url and user_admin_url filters. This parameter is used for giving context to the URL (such as http, https, login, login_post, admin, relative or null) and was already present in other URL related filters (home_url, rest_url, site_url, to name a few).

For more information, see #52813.

Posts/Post Types: Improve post_exists() query

In previous releases, the post_exists() function did not make use of the database indexes available and was generating a poorly performing query. A new $status parameter has been added to allow developers to specify post_type, post_date and post_status to ensure that the wp_posts table’s type_status_date index is used when determining if a post exists.

For more information, see #34012.

Themes: Introduce the delete_theme and deleted_theme action hooks

These new theme action hooks bring parity to the plugin deletion process and fire immediately before and after an attempt to delete a theme, respectively.

For more information see #16401.

Posts/Post Types: Revisions are now enabled for Reusable Blocks post type

As per ticketticket Created for both bug reports and feature development on the bug tracker. #53072, the wp_block post type –which is used for Reusable blocks– now supports revisions. It allows users and developers to rely on revision history for their Reusable blocks.

Changes in the_password_form filter

As per ticket #29008, the the_password_form filter now passes the post object so it can be used by developers to directly get the current post data when they override the password form rendering. This closes a long awaited ticket.

Revisions: Add a post type-specific filter to wp_revisions_to_keep()

A new wp_{$post_type}_revisions_to_keep filter has been added that makes it convenient to filter the number of revisions created for a specific post type.

This new filter will override both the value of WP_POST_REVISIONS and the wp_revisions_to_keep filter.

For more information, see #51550.


Last modified on Thursday July 1, 2021 at 10:43 UTC.

Props @desrosj, @azaozz and @audrasjb for review and additional content.

#5-8, #dev-notes

Block supports API updates for WordPress 5.8

Expanding on previously implemented 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. supports in WordPress 5.6 and 5.7, WordPress 5.8 introduces several new block supports flags and new options to customize your registered blocks.

New Supports

color._experimentalDuotone – Adding duotone support to your block is a new experimental feature. To test, set this property to a string that specifies the CSSCSS Cascading Style Sheets. selector where you want to apply duotone. For example, in your block metadata:

supports: {
    color: {
        _experimentalDuotone: '> .duotone-img'
    }
}

color.link – Support for link color was added, this mirrors the usage and support for color.text that was added in WP 5.6.

To use in your block, add the supports flag in the block metadata:

supports: {
    color: {
        link: true;
    }
}

You can define a default value, using attributes and it will also use the values set in theme.json if present. For example:

attributes: {
  style: {
      type: 'object',
      default: {
          color: {
              link: '#FF0000',
          }
      }

Related ticketticket Created for both bug reports and feature development on the bug tracker.: #31524

Stabilized Supports 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.

Two features that were experimental in WordPress 5.7 have been stabilized in WordPress 5.8

  • fontSize previously __experimentalFontSize
  • lineHeight previously __experimentalLineHeight

See Block Supports API documentation for usage details.

The spacing support was updated and expanded to work for server-side blocks, as well as adding granular support to configure spacing for sides (top, right, bottom, left) individually. For example:

supports: {
    spacing: {
        margin: true,  // Enable margin UI control.
        padding: true, // Enable padding UI control.
    }
}

The following example configures side support for just top and bottom:

supports: {
    spacing: {
        margin: [ 'top', 'bottom' ], // Enable margin for arbitrary sides.
        padding: true,               // Enable padding for all sides.
    }
}

The spacing supports can target specific blocks using theme.json, or it’s own attributes. For example, customizing the top and bottom margins for the core/separator block:

"styles": {
    "blocks": {
        "core/separator": {
            "spacing": {
                "margin": {
                    "top": "100px",
                    "bottom": "100px"
                }
            }
        }
    }
}

Props to @mkaz and @nosolosw for help with compiling this dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase..

Related PRs: #31808, #31332

Tags: #5.8 #dev-notes #gutenberg

#5-8

Introducing theme.json in WordPress 5.8

WordPress 5.8 comes with a new mechanism to configure the editor that enables a finer-grained control and introduces the first step in managing styles for future WordPress releases.

Controlling settings globally and per 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.

The introduction of blocks has increased the number of settings agencies and developers may need control over. Having a central point of configuration aims to provide a more consistent and complete experience.

By creating a theme.json file in the theme’s top-level directory, themes can configure the existing editor settings (the font sizes preset, whether custom colors are enabled, etc.) as well as the new ones as they are introduced (the duotone preset, whether margin and padding controls are enabled, etc.).

This new mechanism aims to take over and consolidate all the various add_theme_support calls that were previously required for controlling the editor.

The example below shows how to disable custom colors for all blocks:

{
    "version": 1,
    "settings": {
        "color": {
            "custom": false
        }
    }
}

The addition of the theme.json file also provides a way for theme authors to control these settings on a per-block basis ― something that wasn’t possible before. The example below shows how to disable custom colors for all blocks but enable them for the paragraph block:

{
    "version": 1,
    "settings": {
        "color": {
            "custom": false
        },
        "blocks": {
            "core/paragraph": {
                "color": {
                    "custom": true
                }
            }
        }
    }
}

Top-level settings will apply to all blocks that support the relevant setting. However, block-level settings can also override the top-level settings for a specific block. Blocks are addressed by their block name and settings can be added for coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. as well as third-party blocks.

Note: to retain backward compatibility, the existing add_theme_support declarations from the theme are retrofitted in the proper categories for the top-level section. For example, if a theme uses add_theme_support('disable-custom-colors'), the result will be the same as setting settings.color.custom to false. If a setting is declared in theme.json that setting will take precedence over the values declared via add_theme_support.

See the specification document for a complete list of features and backcompatibility with add_theme_support.

Blocks can access theme settings with useSetting

Core blocks have been updated to respect the new settings coming from a theme via theme.json. For example, if a block supports a UIUI User interface margin control but the theme has disabled margin across the board, the UI control will not be displayed in the editor.

Third-party blocks can also tap into this mechanism by using the useSetting ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. hook in its edit function:

import { useSetting } from '@wordpress/block-editor';
// Somewhere in the block's edit function.

const isEnabled = useSetting( 'spacing.margin' );

if ( ! isEnabled ) {
    return null;
} else {
    return <ToggleControl ... />
}

See the API docs for useSetting.

CSSCSS Cascading Style Sheets. classes for presets are automatically created and enqueued

Previously, themes had to declare presets for the editor and also enqueue the corresponding classes separately.

In the functions.php file, they’d do:

add_theme_support(
  'editor-color-palette',
  array(  /* define color presets, including translations */
) );

And then, in the style.css:

.has-<value>-color { /* ... */ }
.has-<value>-background-color { /* ... */ }
/* etc */

By using a theme.json, the theme only has to declare their presets. The engine will set up the translations and will take care of creating and enqueuing the corresponding styles to both the editor and the front-end:

{
    "version": 1,
    "settings": {
        "color": {
            "palette": [
                {
                    "name": "Color name",
                    "slug": "color-slug",
                    "color": "<color-value>"
                },
                {
                    "name": "...",
                    "slug": "...",
                    "color": "..."
                }
            ]
        }
    }
}

See the specification document for a list of classes generated by preset.

CSS Custom Properties

By phasing out IE11 support, many CSS features become available. One of these now available features is CSS Custom Properties. When a theme adds presets via theme.json, the engine will enqueue both classes and CSS Custom Properties for them.

The example below:

{
    "version": 1,
    "settings": {
        "color": {
            "palette": [
                {
                    "name": "Black",
                    "slug": "black",
                    "color": "#000000"
                },
                {
                    "name": "White",
                    "slug": "white",
                    "color": "#ffffff"
                }
            ]
        }
    }
}

will create this output in CSS:

/* One CSS Custom Property per preset value. */
body {
  --wp--preset--color--black: #000000;
  --wp--preset--color--white: #ffffff;
}

/* The corresponding classes for each preset value. */

.has-black-color { color: var(--wp--preset--color--black) !important; }
.has-black-background-color { background-color: var(--wp--preset--color--black) !important;  }

.has-white-color { color: var(--wp--preset--color--white) !important; }
.has-white-background-color { background-color: var(--wp--preset--color--white) !important;  }

See the specification document for more examples, how to add and use custom properties unrelated to presets, etc.

Managed styles for improved coordination

One of the struggles theme authors face is the conflicts that appear in an environment with core, theme, and user styles as well as the wide design area that comes with multiple blocks that can be combined indefinitely.

The theme.json file absorbs most of the common use cases for styling blocks with the goal of reducing the amount of CSS shipped to the browser, mitigating specificity wars, and providing current style info in the UI controls for users. This is the first step in having a mechanism that consolidates all the three origins of styles (core, theme, user) and that will become more important once users can provide global styles in later phases of the project.

In the example below, a theme provides styles for the top-level and a couple of blocks:

{
    "version": 1,
    "styles": {
        "color": {
            "text": "var(--wp--preset--color--primary)"
        },
        "blocks": {
            "core/paragraph": {
                "color": {
                    "text": "var(--wp--preset--color--secondary)"
                }
            },
            "core/group": {
                "color": {
                    "text": "var(--wp--preset--color--tertiary)"
                }
            }
        }
    }
}

It results in the following CSS output:

/* Top-level styles resolve to the body selector. */
body {
  color: var(--wp--preset--color--primary);
}

/* Block styles resolve to the block selector. */
p {
  color: var(--wp--preset--color--secondary);
}
.wp-block-group {
  color: var(--wp--preset--color-tertiary);
}

Any block, both core and third-party, can be targeted by its name.

See the specification document for a complete list of supported styles.

Access to other features

There are some features that are enabled or disabled when a theme has support for a theme.json file:

  • The template editor is enabled.
  • The default layout and margin styles for themes are not enqueued and the new layout options are enabled instead (see related dev note for layout).
  • The inner div for the group block (wp-block-group__inner-container) is removed.
  • The default font-family styles for the editor are not enqueued.

#5-8 #dev-notes #gutenberg

Block API Enhancements in WordPress 5.8

Starting in WordPress 5.8 release, we encourage using the block.json metadata file as the canonical way to register 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. types. The Block Metadata specification has been implemented and iterated over the last few major WordPress releases, and we have reached the point where all planned features are in place.

Example File

Here is an example block.json file that would define the metadata for a 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 create a notice block.

notice/block.json

{
	"apiVersion": 2,
	"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
	},
	"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"
}

Benefits using the metadata file

The block definition allows code sharing between 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/., PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher, and other languages when processing block types stored as JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML., and registering blocks with the block.json metadata file provides multiple benefits on top of it.

From a performance perspective, when themes support lazy loading assets, blocks registered with block.json will have their asset enqueuing optimized out of the box. The frontend CSSCSS Cascading Style Sheets. and JavaScript assets listed in the style or script properties will only be enqueued when the block is present on the page, resulting in reduced page sizes.

Furthermore, because the Block Type REST API Endpoint can only list blocks registered on the server, registering blocks server-side is recommended; using the block.json file simplifies this registration.

Last, but not least, the WordPress Plugins Directory can detect block.json files, highlight blocks included in plugins, and extract their metadata. If you wish to submit your block(s) to the Block Directory, all blocks contained in your plugin must have a block.json file for the Block Directory to recognize them.

Block registration

PHP

The register_block_type function that aims to simplify the block type registration on the server, can read now metadata stored in the block.json file.

The function takes two params relevant in this context ($block_type accepts more types and variants):

  • $block_type (string) – path to the folder where the block.json file is located or full path to the metadata file if named differently.
  • $args (array) – an optional array of block type arguments. Default value: []. Any arguments may be defined.

It returns the registered block type (WP_Block_Type) on success or false on failure.

Example:

notice/notice.php

<?php

register_block_type(
	__DIR__,
	array(
		'render_callback' => 'render_block_core_notice',
	)
);

Note: We decided to consolidate the pre-existing functionality available with register_block_type_from_metadata method into register_block_type to avoid some confusion that it created. It’s still possible to use both functions, but we plan to use only the shorter version in the official documents and tools from now on.

Related TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker.#53233.

JavaScript

When the block is registered on the server, you only need to register the client-side settings on the client using the same block’s name.

Example:

notice/index.js

registerBlockType( 'my-plugin/notice', {
	edit: Edit,
	// ...other client-side settings
} );

Although registering the block also on the server with PHP is still recommended for the reasons above, if you want to register it only client-side you can now use registerBlockType method from @wordpress/blocks package to register a block type using the metadata loaded from block.json file.

The function takes two params:

  • $blockNameOrMetadata (string|Object) – block type name (supported previously) or the metadata object loaded from the block.json file with a bundler (e.g., webpack) or a custom Babel plugin.
  • $settings (Object) – client-side block settings.

It returns the registered block type (WPBlock) on success or undefined on failure.

Example:

notice/index.js

import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import metadata from './block.json';

registerBlockType( metadata, {
	edit: Edit,
	// ...other client-side settings
} );

Related PR: WordPress/gutenberg#32030.

Internationalization support in block.json

WordPress string discovery system can now automatically translate fields marked as translatable in Block Metadata document. First, in the block.json file that provides block metadata, you need to set the textdomain property and fields that should be translated.

Example:

fantastic-block/block.json

{
	"name": "my-plugin/fantastic-block",
	"title": "My block",
	"description": "My block is fantastic",
	"keywords": [ "fantastic" ],
	"textdomain": "fantastic-block"
}

PHP

In PHP, localized properties will be automatically wrapped in _x function calls on the backend of WordPress when executing register_block_type function. These translations get added as an inline script to the plugin’s script handle or to the wp-block-library script handle in WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..

The way register_block_type processes translatable values is roughly equivalent to the following code snippet:

<?php
$metadata = array(
	'title'       => _x( 'My block', 'block title', 'fantastic-block' ),
	'description' => _x( 'My block is fantastic!', 'block description', 'fantastic-block' ),
	'keywords'    => array( _x( 'fantastic', 'block keyword', 'fantastic-block' ) ),
);

Implementation follows the existing get_plugin_data function which parses the plugin contents to retrieve the plugin’s metadata, and it applies translations dynamically.

Related Trac ticket: #52301.

JavaScript

You can also now use registerBlockType method from @wordpress/blocks package to register a block type that uses translatable metadata stored in block.json file. All localized properties get automatically wrapped in _x function calls (from @wordpress/i18n package) similar to how it works in PHP with register_block_type. The only requirement is to set the textdomain property in the block.json file.

Example:

fantastic-block/index.js

import { registerBlockType } from '@wordpress/blocks';
import Edit from './edit';
import metadata from './block.json';

registerBlockType( metadata, {
	edit: Edit,
	// ...other client-side settings
} );

Related PR: WordPress/gutenberg#30293.

Extracting translations

The ongoing effort to improve the internationalization of client-side JavaScript code made necessary by moving to the block-based editor has led to several improvements to the i18n make-pot command from WP-CLI as of v2.5.0 release. It now also parses the block.json file as it is defined in the Block Metadata document.

Related PR: wp-cli/i18n-command#210.

New filters

There are two new WordPress 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. that can be used when block types get registered with register_block_type function using the metadata loaded from the block.json file.

block_type_metadata

Filters the raw metadata loaded from the block.json file when registering a block type. It allows applying modifications before the metadata gets processed.

The 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. takes one param:

  • $metadata (array) – metadata loaded from block.json for registering a block type.

Example:

<?php

function filter_metadata_registration( $metadata ) {
	$metadata['apiVersion'] = 1;
	return $metadata;
};
add_filter( 'block_type_metadata', 'filter_metadata_registration', 10, 2 );

register_block_type( __DIR__ );

block_type_metadata_settings

Filters the settings determined from the processed block type metadata. It makes it possible to apply custom modifications using the block metadata that isn’t handled by default.

The filter takes two params:

  • $settings (array) – Array of determined settings for registering a block type.
  • $metadata (array) – Metadata loaded from the block.json file.

Example:

function filter_metadata_registration( $settings, $metadata ) {
	$settings['api_version'] = $metadata['apiVersion'] + 1;
	return $settings;
};
add_filter( 'block_type_metadata_settings', 'filter_metadata_registration', 10, 2 );
		
register_block_type( __DIR__ );

Props to @priethor and @audrasjb for help with compiling this dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include a description of the change, the decision that led to this change, and a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase..

#5-8, #dev-notes, #gutenberg

A Week in Core – June 21, 2021

Welcome back to a new issue of Week in CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. Let’s take a look at what changed on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. between June 14 and June 21, 2021.

  • 58 commits
  • 61 contributors
  • 83 tickets created
  • 7 tickets reopened
  • 52 tickets closed

Please note that the WordPress Core team released WordPress 5.8 beta 2 last week. Everyone is welcome to help testing the next 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. of WordPress 🌟

Ticketticket Created for both bug reports and feature development on the bug tracker. numbers are based on the Trac timeline for the period above. The following is a summary of commits, organized by component and/or focus.

Code changes

Administration

  • Consistently escape admin_url() links – #53426
  • Consistently escape network_admin_url() links – #53459

Build/Test Tools

  • Ignore sourceMaps for non WordPress Core files – #52689
  • Replace the deprecated @babel/polyfill#52941
  • Use 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/. when fetching the WordPress Importer for use in tests – #52909
  • Correct svn:eol-style property for test data with CR line endings – #52625
  • Make some optional parameters required in unit tests for previous/next attachment links – #45708, #52625
  • Use more appropriate assertions in clean_dirsize_cache() tests – #52625
  • Use more appropriate assertions in a few tests – #52625

Bundled Themes

  • Improve 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/ check before activating an FSE theme – #53410
  • Make sure get_file_data() recognizes headers prefixed by <?php 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.)#33387
  • Prevent a Full Site Editing theme from being activated when Gutenberg is not active – #53410
  • Remove unexpected border around the Theme Details button – #53473
  • Twenty Thirteen: Improve the display of the Query LoopLoop The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post. https://codex.wordpress.org/The_Loop. 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.#53438
  • Twenty Twenty-One: Add margins around content in Post Template block – #53389, #53398

Coding Standards

  • Apply some alignment fixes – #50105
  • Bring some consistency to HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. formatting in wp-admin/comment.php#52627
  • Fix WPCSWPCS The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the WordPress Coding Standards. May also be an acronym referring to the Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook. issue in [51174]#53407
  • Remove a one-time $message variable in WordPress version requirement notices for bundled themes – #52627
  • Remove a one-time $message variable in some _doing_it_wrong() calls – #52627
  • Use consistent formatting for _wp_posts_page_notice() and _wp_block_editor_posts_page_notice()#45537, #52627

Documentation

  • Add a reference to WP_Site_Query::__construct() for information on accepted arguments in get_sites()#42156
  • Add missing documentation for wp_migrate_old_typography_shape()#52991, #52628
  • Correct DocBlockdocblock (phpdoc, xref, inline docs) formatting for Core_Upgrader::upgrade()#52628
  • Correct @since version in the wp-includes/version.php file headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes.#52628
  • Document the VALID_ORIGINS constant in WP_Theme_JSON#52628
  • Document the usage of $_wp_current_template_content global in a few block template functions – #52628
  • Document the usage of $wp_embed global in WP_oEmbed_Controller::get_proxy_item()#52628
  • Update syntax for multi-line comment in wp_generate_attachment_metadata() per the documentation standards – #52603
  • Update syntax for some multi-line comments per the documentation standards – #52628

Editor

  • Remove code from a translatable string in wp_migrate_old_typography_shape()#52991
  • Allow custom-units to be an array – #53472
  • Check if supports metadata key is defined before migrating typography keys – #53416
  • Include Cover block in the list of block types registered using metadata files – #53440
  • Replace a Gutenberg specific function with the Core equivalent – #53369
  • Package updates 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 – #53397
  • Prevent duplicate queries – #53280, #53176
  • Second batch of fixes for 5.8 beta 2 – #53397
  • Update the WordPress packages with the fixes for 5.8 beta 2 – #53397
  • Ports theme.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. changes for beta 3 – #53397

External Libraries

  • Upgrade PHPMailer to version 6.5.0 – #53430

Internationalization

  • Remove redundant default text domain parameter in some __() calls – #52627
  • Use consistent pattern for placeholder references in translator comments for some bundled theme strings – #52628

Media

  • Adapt response shape depending on type of query – #53421, #53419
  • Ensure $post_ids is evaluated properly when processing bulk actions – #53411
  • Improve upload page media item layout on smaller screens – #51754
  • Make sure wp_generate_attachment_metadata() always returns an array – #52603
  • Restore AJAX response data shape in media library – #50105
  • Update total attachment count when media added or removed – #53171

Quick/Bulk Edit

  • Ensure that $post_ids variable is initialized ahead of usage – #39589, #53411

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/.

  • Decode HTML entities in widgetWidget A WordPress Widget is a small block that performs a specific function. You can add these widgets in sidebars also known as widget-ready areas on your web page. WordPress widgets were originally created to provide a simple and easy-to-use way of giving design and structure control of the WordPress theme to the user. names and descriptions in widget types controller – #53407
  • Decode single and double quote entities in widget names and descriptions – #53407

Upgrade/Install

  • Deactivate the Gutenberg 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 if its version is 10.7 or lower – #53432

Users

  • Escape get_author_posts_url() link in wp_list_authors()#50698

Widgets

  • Add editor styles to the widgets block editor – #53344, #53388
  • Stop loading wp-editor and the Block Directory assets on the widgets screen – #53437, #53397

Props

Thanks to the 61 people who contributed to WordPress Core on Trac last week: @desrosj (6), @noisysocks (5), @nosolosw (4), @youknowriad (4), @ryelle (4), @adamsilverstein (3), @audrasjb (3), @walbo (3), @SergeyBiryukov (3), @peterwilsoncc (3), @chintan1896 (3), @jorbin (3), @hellofromTonya (3), @david.binda (2), @joedolson (2), @ramonopoly (2), @gziolo (2), @jorgefilipecosta (2), @spacedmonkey (2), @mukesh27 (2), @Presskopp (2), @alexstine (1), @jnylen0 (1), @czapla (1), @francina (1), @markparnell (1), @kraftner (1), @justinahinon (1), @afragen (1), @johnbillion (1), @ayeshrajans (1), @TimothyBlynJacobs (1), @Synchro (1), @Chouby (1), @aristath (1), @ntsekouras (1), @mcsf (1), @chaion07 (1), @Clorith (1), @ocean90 (1), @pbiron (1), @chanthaboune (1), @Mamaduka (1), @mkaz (1), @joen (1), @isabel_brison (1), @andraganescu (1), @caseymilne (1), @sabernhardt (1), @marybaum (1), @AlePerez92 (1), @azaozz (1), @scruffian (1), @birgire (1), @felipeelia (1), @dd32 (1), @m_uysl (1), @thomas-vitale (1), @boblinthorst (1), @oglekler (1), and @JeffPaul (1).

Congrats and welcome to our 3 new contributors of the week! @czapla, @caseymilne, and @AlePerez92 ♥️

Core committers: @sergeybiryukov (33), @desrosj (13), @joedolson (3), @jorgefilipecosta (2), @youknowriad (2), @ryelle (1), @peterwilsoncc (1), @antpb (1), @davidbaumwald (1), and @jorbin (1).

#5-8, #week-in-core

Extending the Site Health interface in WordPress 5.8

With WordPress 5.8, the feature requestfeature request A feature request should generally begin the process in the ideas forum, on a mailing list, as a plugin, or brought to the attention of the core team, such as through scope meetings held for each major release. Unsolicited tickets of this variety are typically, therefore, discouraged. to allow developers to extend what Site Health tabs are available (#47225) has been implemented.

This will allow developers to add their own interfaces to the Site Health area of coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., with accompanying tab navigation in the Site Health headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes., or even extend another interface.

Site Health screen showing 4 navigation items

Registering your tab navigation

If you are adding a brand new interface, you will want to introduce a navigation element, so that users may access your interface. This is done using the new site_health_navigation_tabs 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 is an associated array of tab keys, and their label.

<?php
function wp_example_site_health_navigation_tabs( $tabs ) {
	// translators: Tab heading for Site Health navigation.
	$tabs['example-site-health-tab'] = esc_html_x( 'My New Tab', 'Site Health', 'text-domain' );

	return $tabs;
}
add_filter( 'site_health_navigation_tabs', 'wp_example_site_health_navigation_tabs' );

The above example will add the identifier example-site-health-tab with the label My New Tab to the header navigation i Site Health pages.

It is also possible to re-order what tabs are displayed first using this filter, or even remove tabs. By default core has two tabs, the Status and Info screens. The Status screen is the default, and therefore has no slug.

To not overburden the navigation area, if there are more than 4 items added, only the first three will be displayed directly, with the remaining items being wrapped inside a sub-navigation. This is based on usage testing in the Health Check 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, where 4 items have shown to be enough to cover most use cases, but not so many as to become confusing.

Displaying, or extending, an interface

When a user visits a Site Health tab, other than the default screen, the site_health_tab_content action triggers. This action includes a single argument being the slug, as defined by the tab navigation in the previous filter, to help you identify which page is being requested.

The action fires after the header itself has been loaded, but does not include any wrappers. This gives you as a developer the full width of the screen (not counting the adminadmin (and super admin) menu) to work with.

<?php
function wp_example_site_health_tab_content( $tab ) {
	// Do nothing if this is not our tab.
	if ( 'example-site-health-tab' !== $tab ) {
		return;
	}

	// Include the interface, kept in a separate file just to differentiate code from views.
	include trailingslashit( plugin_dir_path( __FILE__ ) ) . 'views/site-health-tab.php';
}
add_action( 'site_health_tab_content', 'wp_example_site_health_tab' );

The above example loads in a file with your tab content from your plugin, but only if the tab matches the tab key (or slug if you will) which was defined in the previous example.

It is possible to provide output on any tab this way, or on another tab not your own, for example if they interact with each other.

One such example might be to extend the default Info tab, which has the slug debug, and add a button to copy some information specific to only your plugin or theme.

Props @afragen for review and edits.

#5-8, #dev-notes, #site-health

Dev Chat Agenda for June 23, 2021

Here is the agenda for this week’s developer meetings to occur at the following times: June 23, 2021 at 5:00 UTC and June 23, 2021 at 20:00 UTC.

Blogblog (versus network, site) Post Highlights

5.8 Schedule Review

  • 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 released yesterday and a soft string freeze, our focus now shifts to RCrelease 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). phase with RC1 release in 6 days on Tuesday, June 29th
  • Focus now on publishing Dev Notes and eventual Field GuideField guide The field guide is a type of blogpost published on Make/Core during the release candidate phase of the WordPress release cycle. The field guide generally lists all the dev notes published during the beta cycle. This guide is linked in the about page of the corresponding version of WordPress, in the release post and in the HelpHub version page., committing the About page, drafting the release post, and a hard string freeze
  • Next Beta Scrub before RC 1 is Monday, June 28th 20:00 UTC
  • RC 1 in 6 days on Tuesday, June 29th
  • 5.8 release in 27 days on Tuesday, July 20th

Components check-in and status updates

  • 5.8 plans and help needed
  • Check-in with each component for status updates.
  • Poll for components that need assistance.

Open Floor

Do you have something to propose for the agenda, or a specific item relevant to the usual agenda items above?

Please leave a comment, and say whether or not you’ll be in the chat, so the group can either give you the floor or bring up your topic for you accordingly.

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

#5-8, #agenda, #dev-chat

Bundled themes changes in WordPress 5.8

Since 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. patterns were introduced in WordPress 5.5, older default themes received some block patterns love in 5.8. 

Twenty Fifteen

Twenty Fifteen now has: 

  • Gallery and Description
  • Contact area
  • Two Columns with Images, and 
  • Columns with a List block patterns. 

They can be found under the Twenty Fifteen block pattern categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging..

Related ticketticket Created for both bug reports and feature development on the bug tracker.: #51102 

Twenty Fourteen

Twenty Fourteen has following block patterns:

  • About,
  • List,
  • Summary, and
  • Contact.

These patterns can be found under the Twenty Fourteen block pattern category.

Related ticket: #51103 

Twenty Thirteen

Twenty Thirteen is decorated with:

  • Decorative Gallery,
  • Informational Section,
  • Decorative Columns,
  • Callout Quote,
  • Big Quote, and
  • Informational List block patterns.

All of these are registered under the Twenty Thirteen block pattern category.

Related ticket: #51104 

Twenty Twelve

Twenty Twelve has:

  • Floating Images Gallery,
  • Left-aligned Large Quote, and
  • Left-aligned Image and Paragraph block patterns.

These patterns are registered under the, you guessed it, Twenty Twelve block pattern category.

Related ticket: #51105 

Twenty Eleven

Twenty Eleven patterns:

  • Image and Text Columns,
  • Inline Quote,
  • Follow Blogblog (versus network, site),
  • About Me, and
  • Two Columns of Lists.

Patterns can be found under the Twenty Eleven block pattern category.

Related ticket: #51106 

Twenty Ten

Twenty Ten theme got three block patterns:

  • Introduction,
  • Highlighted Quote, and
  • Alternating Images.

Patterns are registered under the Twenty Ten block patterns category.

Related ticket: #51107 

These new block patterns will be very helpful for end users, especially combined with a new template editor introduced in WordPress 5.8, as well as new theme blocks. 

#5-8, #dev-notes