Recommended usage of the Updates API to support the auto-updates UI for Plugins and Themes in WordPress 5.5

This is an addendum to Controlling Plugin and Theme auto-updates UI in WordPress 5.5.

Edit 8/05/2020: An error in the example of populating no_updates for plugins has been corrected: in site_transient_update_plugins the value of response and no_update are arrays of objects; whereas in site_transient_update_themes, they are arrays of arrays. props @afragen. @pbiron

By default, the enable and disable auto-updates action links for plugins (detailed in the previous developer note) will only appear when the WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Updates 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. (available since version 3.7.0) is supported.

All plugins that are hosted in the WordPress Plugin Directory and themes that are hosted in the WordPress Theme Directory already fully support the Updates API and require no changes.

Plugins and themes that are hosted elsewhere (such as premium or “private” plugins) can also support the Updates API with a little bit of code.

Though there is currently no one “official” way for such plugins to support the Updates API, this note offers recommendations for how developers can provide enough support for the auto-updates UIUI User interface to work for their plugins.

Filtering the 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 update transient

The responses received from querying the WordPress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/ Updates API are stored in the update_plugins site transient. There are several existing filters that developers can use to add information about the availability or lack of available updates for a specific plugin that is not hosted in the WordPress Plugin Directory to that transient. The most common are:

Using pre_set_site_transient_update_plugins, for example, developers can do:

<?php
function myplugin_pre_set_site_transient_update_plugins( $transient ) {
	// Query premium/private repo for updates.
	$update = myplugin_check_for_updates( 'my-plugin' );
	if ( $update ) {
		// Update is available.
		// $update should be an array containing all of the fields in $item below.
		$transient->response['my-plugin/my-plugin.php'] = $update;
	} else {
		// No update is available.
		$item = (object) array(
			'id'            => 'my-plugin/my-plugin.php',
			'slug'          => 'my-plugin',
			'plugin'        => 'my-plugin/my-plugin.php',
			'new_version'   => $myplugin_current_version,
			'url'           => '',
			'package'       => '',
			'icons'         => array(),
			'banners'       => array(),
			'banners_rtl'   => array(),
			'tested'        => '',
			'requires_php'  => '',
			'compatibility' => new stdClass(),
		);
		// Adding the "mock" item to the `no_update` property is required
		// for the enable/disable auto-updates links to correctly appear in UI.
		$transient->no_update['my-plugin/my-plugin.php'] = $item;
	}

	return $transient;
}

add_filter( 'pre_set_site_transient_update_plugins', 'myplugin_pre_set_site_transient_update_plugins' );

Developers that have already been using the Updates API to offer updates for their plugins that are not hosted in the WordPress Plugins Directory have already been populating the response property for their plugin.

The no_update property is a requirement for the auto-update UI to work correctly for externally hosted plugins.

Some are already populating the no_update for their plugin. Any that are not should update their code accordingly for the best user experience.

Filtering the theme update transient

For themes, the responses received from querying the WordPress.org Updates API are stored in the update_themes site transient. The filters used to modify the values of these transients are similar to the ones used for plugins but slightly different:

Using pre_set_site_transient_update_themes, for example, developers of a theme hosted in a different location can do:

<?php
function mytheme_pre_set_site_transient_update_themes( $transient ) {
	// Query premium/private repo for updates.
	$update = mytheme_check_for_updates( 'my-theme' );
	if ( $update ) {
		// Update is available.
		// $update should be an array containing all of the fields in $item below.
		$transient->response['my-theme'] = $update;
	} else {
		// No update is available.
		$item = array(
			'theme'        => 'my-theme',
			'new_version'  => $mytheme_current_version,
			'url'          => '',
			'package'      => '',
			'requires'     => '',
			'requires_php' => '',
		);
		// Adding the "mock" item to the `no_update` property is required
		// for the enable/disable auto-updates links to correctly appear in UI.
		$transient->no_update['my-theme'] = $item;
	}

	return $transient;
}

add_filter( 'pre_set_site_transient_update_themes', 'mytheme_pre_set_site_transient_update_themes' );

The no_update property was only recently added to API responses for theme update queries, and like plugins, the no_update property is a requirement for the auto-update UI to work correctly for externally hosted themes.

Props @desrosj and @audrasjb for review prior to publishing.

#5-5, #auto-update, #auto-updates, #dev-notes, #feature-autoupdates

Themes field guide: WordPress 5.5

WordPress 5.5 will contain several changes to existing features that will directly impact themes. This theme specific 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. details a few changes and also links several that were previously published separately.

Theme compatibility checks

In WordPress 5.4, support was added to the style.css file for the RequiresWP (Requires at least) and RequiresPHP (Requires PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher) file headers (see #44592). These headers allow theme authors to define the minimum versions of WordPress and PHP required to reliably run their themes. Though support was added for these headers, they were not yet used in CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..

In 5.5, the values provided by these headers will now be respected. Users will be unable to install, activate, or preview themes when a site does not meet the specified requirements.

Please ensure your theme contains these headers, and that the values are up to date and accurate.

For more information, check out the related tickets on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. (#48491, #48507, #49334, #49653).

Adding icons in Twenty Twenty

The Twenty Twenty default theme includes a feature that displays SVG icons to a page from a defined list if available icons. Additionally, there is an array that maps icon names to specific social website URLs. When a menu is assigned to the social menu location, the link text is automatically replaced with logo icons for each link (should one match the predefined list of supported icons).

Continuing to add requested icons (there are a small handful every few months) is not sustainable. Because of this, no new requests for icons will be considered for the Twenty Twenty theme. However, filters have been added in the theme to allow additional icons to be added as desired.

  • The twentytwenty_svg_icons_{$group} 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. allows new SVG icon tags to be added to a group’s list of icons. The default groups are ui (twentytwenty_svg_icons_ui), and social (twentytwenty_svg_icons_social). Custom groups could be added if needed.
  • The twentytwenty_social_icons_map filter allows new services to be added to the list of site links that are automatically replaced with icons in a menu assigned to the social menu location.
  • And finally, the new twentytwenty_svg_icon_color filter allows the color of the icon being displayed to be changed.

For example, say you wish to replace the calendar icon provided by default with your own.

<?php
function mychildtheme_twentytwenty_svg_icons_ui( $icons ) {
	$icons['calendar'] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M6.75 0a.75.75 0 01.75.75V3h9V.75a.75.75 0 011.5 0V3h2.75c.966 0 1.75.784 1.75 1.75v16a1.75 1.75 0 01-1.75 1.75H3.25a1.75 1.75 0 01-1.75-1.75v-16C1.5 3.784 2.284 3 3.25 3H6V.75A.75.75 0 016.75 0zm-3.5 4.5a.25.25 0 00-.25.25V8h18V4.75a.25.25 0 00-.25-.25H3.25zM21 9.5H3v11.25c0 .138.112.25.25.25h17.5a.25.25 0 00.25-.25V9.5z"></path></svg>';

	return $icons;
}
add_filter( 'twentytwenty_svg_icons_ui', 'mychildtheme_twentytwenty_svg_icons_ui' );

As a second example, say you have a separate photography blogblog (versus network, site) and would like to add a link in your social navigation.

<?php
function mychildtheme_twentytwenty_social_icons_map( $icons ) {
	$icons['myphotoblog'] = array(
		'myphotoblogdomain.com',
		'asecondphotoblogdomain.com',
	);

	return $icons;
}
add_filter( 'twentytwenty_social_icons_map', 'mychildtheme_twentytwenty_social_icons_map' );

function mychildtheme_twentytwenty_svg_icons_social( $icons ) {
	$icons['myphotoblog'] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill-rule="evenodd" d="M2.25 4a.25.25 0 00-.25.25v15.5c0 .138.112.25.25.25h3.178L14 10.977a1.75 1.75 0 012.506-.032L22 16.44V4.25a.25.25 0 00-.25-.25H2.25zm3.496 17.5H21.75a1.75 1.75 0 001.75-1.75V4.25a1.75 1.75 0 00-1.75-1.75H2.25A1.75 1.75 0 00.5 4.25v15.5c0 .966.784 1.75 1.75 1.75h3.496zM22 19.75v-1.19l-6.555-6.554a.25.25 0 00-.358.004L7.497 20H21.75a.25.25 0 00.25-.25zM9 9.25a1.75 1.75 0 11-3.5 0 1.75 1.75 0 013.5 0zm1.5 0a3.25 3.25 0 11-6.5 0 3.25 3.25 0 016.5 0z"></path></svg>';

	return $icons;
}
add_filter( 'twentytwenty_svg_icons_social', 'mychildtheme_twentytwenty_svg_icons_social' );

For more information on this change, check out #48713 on Trac.

The icons in the examples above courtesy of Octicons.

Other theme related updates

There are several other changes affecting themes that were published as separate developer notes. You can find them below for easy reference.

For a full list of developer notes associated with WordPress 5.5 (including those documenting new features), please read the full WordPress 5.5 field guide.

Props @audrasjb for reviewing prior to publish.

#5-5, #dev-notes

Controlling Plugin and Theme auto-update email notifications and Site Health infos in WP 5.5

This is the second part of the plugins and themes auto-updates dev notesdev 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. for WordPress 5.5. The first part was dedicated to Controlling Plugins and Themes auto-updates user interface.

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 Theme auto-update email notifications

As of WordPress 5.5, email notifications will be sent after each attempt to auto-update a plugin or theme regardless of outcome (success or failure).

Here’s what you need to know about these emails.

Filtering the emails

Using the auto_plugin_theme_update_email hook, the recipient, subject, headers, and email content can be filtered to adjust a site’s needs.

Example of use:

<?php
function myplugin_auto_plugin_theme_update_email( $email, $type, $successful_updates, $failed_updates ) {
	// Change the email recipient.
	$email['to'] = 'admin@example.com';
	// Change the email subject when updates failed
	if ( 'fail' === $type ) {
		$email['subject'] = __( 'ATTN: IT Department – SOME AUTO-UPDATES WENT WRONG!', 'my-plugin' );
	}

	return $email;
}
add_filter( 'auto_plugin_theme_update_email', 'myplugin_auto_plugin_theme_update_email', 10, 4 );

Repeated failures email notifications prevention

Sometimes, a specific update may fail multiple times. When this happens, a notification email will be sent for only the first failure. A failure is considered a repeat when attempting to update to the same version.

For example, if version 1.0.1 fails and then 1.0.2 is released and fails, that is not a repeat failure.

For more information, see #50448 on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

Disabling email notifications

Email notifications can be disabled using two filters:

  • auto_plugin_update_send_email
  • auto_theme_update_send_email

Emails are enabled by default (true). Returning false to either 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. will disable email notifications for that auto-update type.

The following snippet can be used to disable email notifications for themes and/or plugins auto-updates.

<?php
// Disable auto-update email notifications for plugins.
add_filter( 'auto_plugin_update_send_email', '__return_false' );

// Disable auto-update email notifications for themes.
add_filter( 'auto_theme_update_send_email', '__return_false' );

Auto-updates information in Site Health

Each plugin and theme’s auto-update status is also surfaced on the Site Health “Info” tab.

This text can be adjusted using the plugin_auto_update_debug_string and theme_auto_update_debug_string filters.

The following example replaces the text for the status of auto-updates for plugins:

<?php
function myplugin_plugin_auto_update_debug_string( $text, $plugin, $enabled ) {
	if ( false === $enabled ) {
		return __( 'Please consider turning on auto-updates!', 'my-plugin' );
	} else {
		return __( 'Thanks for enabling auto-updates!', 'my-plugin' );
	}
}
add_filter( 'plugin_auto_update_debug_string', 'myplugin_plugin_auto_update_debug_string', 10, 3 )

The following example replaces the text for the status of auto-updates for themes:

<?php
function mytheme_theme_auto_update_debug_string( $text, $active_theme, $enabled ) {
	if ( false === $enabled ) {
		return __( 'Please consider turning on auto-updates!', 'my-theme' );
	} else {
		return __( 'Thanks for enabling auto-updates!', 'my-theme' );
	}
}
add_filter( 'theme_auto_update_debug_string', 'mytheme_theme_auto_update_debug_string', 10, 3 )

Please note: Site Health support was introduced in the Feature Plugin, so there is no Changelog/Trac ticketticket Created for both bug reports and feature development on the bug tracker. to link.

Reviewed by @pbiron and @desrosj

#5-5, #dev-notes

Filtering archive page headings in WordPress 5.5

With WordPress 5.5, theme authors will now be able to easily 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. archive pages headings, so they can use their own HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. markup.

The existing get_the_archive_title hook was previously limited to filter the whole title string used on archive pages. Some contributors pointed out that this filter was not specific enough to address all theme developers needs related to the archive pages headings.

In get_the_archive_title() this change splits the internal $title variable into $title and $prefix.

By using the new get_the_archive_title_prefix filter, the prefix can now be wrapped within custom elements or removed completely.

Basic examples

get_the_archive_title_prefix can be used to filter the archive pages heading prefix. It accepts only one argument, $prefix, which is a string containing the text prefix of the heading.

To replace the archive title prefix with another text, use:

function mytheme_archive_title_prefix( $prefix ){
    $prefix = __( 'Currently viewing archives for:', 'my-theme' ); 
    return $prefix;
}
add_filter( 'get_the_archive_title_prefix', 'mytheme_archive_title_prefix' );

To completely remove the archive title prefix, use:

add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );

This change also wrap the title part with a span element and pass the original title and prefix to the existing get_the_archive_title filter, allowing further customization to the archive titles.

This filter passes the following arguments:

  • $title: Archive title to be displayed
  • $original_title: Archive title without prefix
  • $prefix: Archive title prefix

Here is a sample example of use:

function mytheme_get_the_archive_title( $title, $original_title, $prefix ) {
    $prefix = '<span class="archive-prefix">' . __( 'Currently viewing archives for:', 'my-theme' ) . '</span>';
    $title  = '<span class="archive-title">' . $original_title . '</span>';
    return $prefix . $title;
}
add_filter( 'get_the_archive_title', 'mytheme_get_the_archive_title', 10, 3 );

For full context on this change, see the related tickets: #31237, #38545 and #42768.

Note reviewed by @justinahinon

#5-5, #dev-notes

Block API Updates in 5.5

Coauthored by @aduth and @gziolo.

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

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

The default set of block categories was updated.

The new set of block categories is:

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

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

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

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

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

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

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

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

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

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

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

   // ...
} );

Block Type Metadata

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

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

Example:

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

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

Block Context

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

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

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

Defining Block Context

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

Providing Block Context

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

record/block.json

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

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

Consuming Block Context

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

record-title/block.json

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

Using Block Context

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

JavaScript

record-title/index.js

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

PHP

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

record-title/index.php

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

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

Various changes to WordPress React Components in WordPress 5.5

BlockPreview component

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

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

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

Popover component

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

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

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

Miscellaneous Developer Focused Changes in WordPress 5.5


Edit 7/29/2020: a call out specific to Twenty Ten was added for the comment_type change.

Edit 8/10/2020: add wp_slash() and adminadmin (and super admin) viewport changes in “Additional developer changes” section.


WordPress 5.5 comes with a number of small developer-focused changes. Here’s a summary of what you can expect.

Upgrade/Install: updating 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 or theme by uploading a ZIP file

Starting in WordPress 5.5, it will be possible to update a plugin or theme by uploading a ZIP file. After uploading the ZIP file, a comparison table will be displayed to the user, detailing the differences between the uploaded ZIP and the version of the plugin currently installed.

The majority of this process is handled by the new do_overwrite() methods within the Theme_Installer_Skin and Plugin_Installer_Skin classes. However, there are a few 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 to adjust the output of this feature:

  • The install_plugin_overwrite_comparison and install_theme_overwrite_comparison filters can be used to modify the output of the comparison tables.
  • The install_plugin_overwrite_actions and install_theme_overwrite_actions filters can be used to modify the actions displayed after an update has failed when overwriting is allowed.
  • The upgrader_overwrote_package action is fired when a plugin or theme has been successfully been upgraded/replaced with a new version uploaded by ZIP.

For more information, refer to #9757 on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

Themes: functions calling locate_template()now have a return value

The template loading functions have historically not returned any values. When called, they execute silently, even if the desired template file is missing. This makes it difficult to debug situations where there is a typo in the template name details passed to the function.

Starting in 5.5, the following functions now return false if the template file is not found, and void if the template is found and loaded:

  • get_header()
  • get_footer()
  • get_sidebar()
  • get_template_part()

This could also be used for themes to check for missing template files and execute code when one is missing. For example:

<?php
if ( false === get_header( 'post' ) ) {
    // Do something when the `header-post.php` file is missing or cannot be loaded.
}

Note: Previously, returning a value when the template was loaded successfully was explored. However, this approach is not feasible. It was discovered that many themes in the wild are printing the return value of get_template_part(), leading to unexpected (and potentially compromising) content being sent to the browser.

For more information, check out the related ticketticket Created for both bug reports and feature development on the bug tracker. on Trac: #40969.

TaxonomyTaxonomy A taxonomy is a way to group things together. In WordPress, some common taxonomies are category, link, tag, or post format. https://codex.wordpress.org/Taxonomies#Default_Taxonomies.: default categories for custom post types

For the post post type, a default categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging. term (“Uncategorized” by default) is applied to every published post. Starting in 5.5, this default term can be applied to posts of any custom post typeCustom Post Type WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Custom Post Types gives your site the ability to have templated posts, to simplify the concept. with the category taxonomy registered to it. This can be accomplished using the new default_category_post_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..

For more information, refer to #43516 on Trac.

Taxonomy: support for default terms in custom taxonomies

A new default_term argument has also been added to register_taxonomy(). Using this argument, a default term name (and optionally slug and description) can be defined. If the defined term does not exist, it will be created automatically.

Additionally, a default_term_$taxonomy option will be added to the database for easy access, and parity with default_category.

For more information, see #43517 on Trac.

Comments: default comment_type value now enforced

Since [9541], an empty string has been used as the default value of a comment’s comment_type field (though it was possible for this to be empty sooner). While examining the possibility of introducing custom comment types in #35214, this was identified as something that would potentially be problematic.

Starting in WordPress 5.5, comment will be enforced as the default comment_type for all comments going forward. This change is one of the first step to open the door to potentially supporting custom comment types.

After upgrading to 5.5, an upgrade routine will be scheduled via cron and run to update all preexisting comments with an empty comment_type to comment. This process will batch comments 100 at a time. The batch size can be adjusted using the wp_update_comment_type_batch_size filter.

If a conditional checks that $comment->comment_type is an empty string in your plugin or theme, it is possible that this change could cause comments to stop displaying on your site. Twenty Ten was the only default theme affected by this. Though it has been fixed and the theme will be updated along with 5.5, any theme built off of Twenty Ten should be updated.

For more information, see the related tickets on Trac (#49236, #35214).

Comments: Changes to return values

With the aim of consistency and WordPress 5.5 will bring a few changes to the values wp_update_comment() returns.

First, a new parameter, $wp_error, has been added to control whether a WP_Error is returned when an error is encountered. This is optional, and will default to false (do not return a WP_Error object).

Second, the return values for an 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. comment or post ID has been changed from 0 to false. This addresses an issue where 0 could be returned for three different scenarios.

Any code checking explicitly for 0 as a returned value of wp_update_comment() will need to be updated to instead explicitly check for false.

For more information, see the related ticket on Trac (#39732).

Additional developer changes

  • Build/Test Tools: The documentation for the Docker environment included with CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. for local development and the environment overall has been improved. Contributors are encouraged to give it a try and report any breakage they experience. (see #50058).
  • Docs: All instances of @staticvar within inline PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher docs have been removed. This 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.) is no longer supported in phpDocumentor (see #50426).
  • Formatting: loading has been added as an allowed attribute for the <img> tag in the KSES functions (see #50731).
  • Formatting: wp_filter_object_list() now properly returns an array when passed an object with magic methods (see #50095).
  • General: The logic in add_magic_quotes() has been adjusted to prevent inappropriately recasting non-string data types to strings. This was noticeable in the REQUEST_TIME and REQUEST_TIME_FLOAT values in the $_SERVER super global (see #48605).
  • Login and Registration: The new lostpassword_errors filter in retrieve_password() allows developers to add or modify the errors generated during a password reset request (see #49521).
  • Media: the media grid frame is now exposed via the wp-media-grid-ready trigger for easier customization (see #50185).
  • Query: A new set_404 action has been introduced, firing after a 404 is triggered (see #48061).
  • Query: The found_posts property of WP_Query will now always be an integer (#42469).
  • Site Health: The error messages displayed to a user when the site does not meet the PHP or WordPress requirements of the plugin being activated have been improved to list those requirements and include a link to support documentation for updating PHP (see #48245).
  • TinyMCE: TinyMCE has been updated to version 4.9.10 (see #50431).
  • Upgrade/Install: an additional hook_extra parameter has been added to the upgrader_pre_download filter. This will provide additional context to code hooked onto this filter, such as which plugin or theme update will be downloaded (see #49686).
  • Upload: a new pre_wp_unique_filename_file_list filter has been added to wp_unique_filename(). This can be used to short-circuit the scandir() call to provide performance improvements for large directories (see #50587).
  • Administration: Remove multiple viewport 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. tags from mobile pages (see #47369).
  • Administration: Introduce the wp_admin_viewport_meta() function, paired to the admin_viewport_meta filter to control attributes of the meta tag (see #47369).
  • Formatting: Prevent wp_slash from returning non-strings as strings (see #42195).

Props @desrosj and @sergeybiryukov for reviewing/helping providing some sections.

#5-5, #dev-notes

Themes: changes related to get_custom_logo() in WordPress 5.5

Update (August 7): Removing the link from the homepage logo will be optional for WordPress 5.5, and a description of how to implement that in themes is now included below. The CSSCSS Cascading Style Sheets. selector change is still recommended for some themes.

Unlinking the custom logo on the homepage

A new unlink-homepage-logo parameter is added for the custom-logo theme support option. By default, unlink-homepage-logo is set to false, and theme authors can opt-in for the change by setting it to true. This would be the array for Twenty Twenty:

add_theme_support(
	'custom-logo',
	array(
		'height'               => $logo_height,
		'width'                => $logo_width,
		'flex-height'          => true,
		'flex-width'           => true,
		'unlink-homepage-logo' => true, // Add Here!
	)
);

If the unlink-homepage-logo parameter is set to true, logo images inserted using get_custom_logo() or the_custom_logo() will no longer link to the homepage when visitors are on that page. In an effort to maintain the styling given to the linked image, the unlinked logo image is inside a span 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.) with the same “custom-logo-link” class.

Many themes include both a logo and a site title, and then the logo is decoration alongside the site title. Because decorative images do not need their purpose to be described, the unlinked logo’s alt attribute would be empty. In cases where the site title is not present, the logo alt text may require custom handling. See code examples below for ways to override the default behavior.

Theme authors who use the a tag as a CSS selector instead of the .custom-logo-link class are encouraged to duplicate their selector to also select the span tag, or to directly select the .custom-logo-link class. A theme directory search found 183 themes that use a.custom-logo-link for styling.

Please verify whether this change makes the logo display any differently on the homepage, as well as whether the empty alt text should be appropriate.

For more details about the homepage logo link, see the related ticketticket Created for both bug reports and feature development on the bug tracker. on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress.: #37011

New logo image attributes 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.

Themes can use the get_custom_logo_image_attributes filter to override default attributes for the logo image or to set additional attributes.

For example, if a theme combines the logo image plus the site title (as actual text) within a link and/or heading tag, then having the site title as the logo’s alt text would be redundant. In that case, this is one way to empty the alt text so screen readers only announce the actual text:

add_filter( 'get_custom_logo_image_attributes', 'my_logo_remove_alt_text', 10, 1 );
function my_logo_remove_alt_text( $custom_logo_attr ) {
	$custom_logo_attr["alt"] = "";
	return $custom_logo_attr;
}

To check whether a user has customized the alt text before emptying it, the filter could be similar to this:

add_filter( 'get_custom_logo_image_attributes', 'my_logo_alt_custom_or_empty', 10, 2 );
function my_logo_alt_custom_or_empty( $custom_logo_attr, $custom_logo_id ) {
	$logo_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
	if ( empty( $logo_alt ) ) {
		$custom_logo_attr["alt"] = "";
	}
	return $custom_logo_attr;
}

If a user has customized the alt text value, this can restore it on the homepage:

add_filter( 'get_custom_logo_image_attributes', 'my_logo_homepage_maybe_alt', 10, 2 );
function my_logo_homepage_maybe_alt( $custom_logo_attr, $custom_logo_id ) {
	$logo_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
	if ( ! empty ( $logo_alt ) && is_front_page() ) {
		$custom_logo_attr["alt"] = $logo_alt;
	}
	return $custom_logo_attr;
}

If the site title is appropriate as a fallback on the homepage in a certain theme, a filter like this could be used:

add_filter( 'get_custom_logo_image_attributes', 'my_logo_homepage_restore_alt', 10, 2 );
function my_logo_homepage_restore_alt( $custom_logo_attr, $custom_logo_id ) {
	$logo_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
	if ( is_front_page() ) {
		if ( ! empty ( $logo_alt ) ) {
			$custom_logo_attr["alt"] = $logo_alt;
		} else {
			$custom_logo_attr["alt"] = get_bloginfo( 'name', 'display' );
		}
	}
	return $custom_logo_attr;
}

For more details about the filter, see the related ticket on Trac: #36640


Props: @joedolson for adding to the explanation and for review; also @audrasjb, @desrosj, @williampatton, and @poena for review

#5-5, #dev-notes

New Block Tools on WordPress 5.5

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

Custom Line Heights

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

add_theme_support( 'custom-line-height' );

Custom Units

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

add_theme_support( 'custom-units' );

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

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

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

Opcode Cache Invalidation in WordPress 5.5

Before 5.5, WordPress relied on hosting provider or user settings and plugins to handle purging or invalidating of coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., 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 theme PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher changes. This resulted in problems for users like PHP fatal errors when a cached file included a file that had been deleted during an update.

As of [48160], WordPress attempts to invalidate PHP files when Core, Plugins, or Themes are updated.

To help with this, a new function is available, wp_opcache_invalidate(), a safe-to-call-directly wrapper for PHP’s native opcache_invalidate(). In order to avoid PHP warnings, the function handles the checks necessary to see whether OPcache is available, and whether invalidation is allowed by the current PHP settings.

function wp_opcache_invalidate( $filepath, $force = false ) 

The function includes a 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., wp_opcache_invalidate_file, which allows disabling WordPress’ invalidation by file, in case it is necessary due to platform concerns, or there are certain files that a user wants to keep from being invalidated.

You can skip invalidation for one file like this:

// Disable opcode cache invalidation for `/path/to/myfile.php`.
function disable_myfile_invalidation( $will_invalidate, $filename ) {
    if ( '/path/to/myfile.php' === $filename ) {
        return false;
    }

    return true;
}
add_filter( 'wp_opcache_invalidate_file', 'disable_myfile_invalidation', 10, 3 );

Or disable it entirely:

// Disable all of WordPress' opcode cache invalidation:
add_filter( 'wp_opcache_invalidate_file', '__return_false' );

Does this change fix the issues you’ve been having with opcode cache invalidation?

Please test and leave a comment here or open a ticket if you run into problems, have concerns, or need additional 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. for your use-case.

Thanks to @aaroncampbell for review!

#5-5, #dev-notes