New block variation APIs in 5.7

New isActive property

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. variation settings can now include a new isActive property. This optional property is a function that is used by the block editor to determine what variation a given block is. This means that block editor UIUI User interface such as BlockCard can display the block variation’s title and description instead of the block’s title and description.

We need this function to be explicitly implemented by block/pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party authors, because in many cases it doesn’t make sense to try to find a match by checking dynamically all block properties. An example is the embed block where we might have changed the responsive attribute, so a match would not be found.

Example in a single block variation:

const variations = [
	{
		name: 'wordpress',
		title: 'WordPress',
		keywords: [ __( 'post' ), __( 'blog' ) ],
		description: __( 'Embed a WordPress post.' ),
		attributes: { providerNameSlug: 'wordpress' },
		isActive: ( blockAttributes, variationAttributes ) =>
			blockAttributes.providerNameSlug ===
			variationAttributes.providerNameSlug,
	},
];

Example when all variations use the same matching function:

const variations = [
	{
		name: 'twitter',
		title: 'Twitter',
		icon: embedTwitterIcon,
		keywords: [ 'tweet', __( 'social' ) ],
		description: __( 'Embed a tweet.' ),
		patterns: [ /^https?:\/\/(www\.)?twitter\.com\/.+/i ],
		attributes: { providerNameSlug: 'twitter', responsive: true },
	},
	{
		name: 'wordpress',
		title: 'WordPress',
		icon: embedWordPressIcon,
		keywords: [ __( 'post' ), __( 'blog' ) ],
		description: __( 'Embed a WordPress post.' ),
		attributes: { providerNameSlug: 'wordpress' },
	},
];

variations.forEach( ( variation ) => {
	if ( variation.isActive ) return;
	variation.isActive = ( blockAttributes, variationAttributes ) =>
		blockAttributes.providerNameSlug ===
		variationAttributes.providerNameSlug;
} );
export default variations;

New useBlockDisplayInformation hook

useBlockDisplayInformation is a new hook that returns display information about a block. It takes into account the isActive property of the each block variation. It returns the block variation or block’s titleicon and description.

If a block variation match cannot be found, the returned information will come from the block type. If no block type is found, then null is returned.

Example usage:

import { useBlockDisplayInformation, BlockIcon } from '@wordpress/block-editor';
function myBlockInformation( clientId ) {
	const blockInformation = useBlockDisplayInformation( clientId );
	if ( ! blockInformation ) return null;
	const { title, icon, description } = blockInformation;
	return (
		<div>
			<BlockIcon icon={ icon } />
			<h2 className="block-title">{ title }</h2>
			<p>{ description }</p>
		</div>
	);
}

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. was written by @ntsekouras and edited by @noisysocks.

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

Improved HTTPS detection and migration in WordPress 5.7

WordPress 5.7 will feature a number of enhancements which simplify the migrationMigration Moving the code, database and media files for a website site from one server to another. Most typically done when changing hosting companies. of a site from HTTPHTTP HTTP is an acronym for Hyper Text Transfer Protocol. HTTP is the underlying protocol used by the World Wide Web and this protocol defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands. to HTTPSHTTPS HTTPS is an acronym for Hyper Text Transfer Protocol Secure. HTTPS is the secure version of HTTP, the protocol over which data is sent between your browser and the website that you are connected to. The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between your browser and the website are encrypted. This is especially helpful for protecting sensitive data like banking information.. As the foundation for providing the user with more accurate recommendations, WordPress will be able to detect whether the current environment already supports HTTPS. If this is the case, it provides a call-to-action button in the HTTPS status section in Site Health, which switches the site from HTTP to HTTPS with a single click.

Overall guidance in the Site Health section has been improved, now allowing hosting providers to supply a custom URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org with instructions or for a one-click update.

Walkthrough of the new feature with a quick demo, including highlighting of the problems this addresses

Detecting state of HTTPS and environment support

WordPress 5.7 introduces a new function wp_is_using_https(), which returns true if both the “Site Address” (home_url()) and “WordPress Address” (site_url()) are using HTTPS as their scheme. Essentially, changing both of these URLs to HTTPS formally indicates that the site is using HTTPS. While there are other ways to enable HTTPS partially in WordPress (e.g. with the FORCE_SSL_ADMIN constant), the new detection mechanism focuses on using HTTPS throughout the entire site, i.e. its frontend and backend.

In addition to providing a single function for checking whether HTTPS is being used, a new detection function wp_is_https_supported() can be called to check whether the environment supports HTTPS correctly. This is now used in Site Health to provide more accurate feedback: If the environment already supports HTTPS, the user can make the switch instantly, without involving their hosting company. Under the hood, the detection function is based on a new internal option https_detection_errors, which is controlled by a twice-daily Cron hook that works as follows:

  • It issues a request to the HTTPS version of the site with the sslverify argument enabled.
    • If the request succeeds, there is already a working SSLSSL Secure Sockets Layer. Provides a secure means of sending data over the internet. Used for authenticated and private actions. certificate in place.
      • In this case, the function also checks whether the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. body from the response actually belongs to the same WordPress site; this is typically the case, but the extra check is needed to cater for sites and environments that e.g. place custom HTML content under the URL. If the HTML body belongs to the same WordPress site, the environment is ready to be switched to HTTPS. Otherwise, switching to HTTPS then cannot reliably be accomplished by WordPress itself because the content is not entirely controlled by it.
    • If the request fails, it attempts the same request again, except that the sslverify argument is now disabled.
      • If that request succeeds, it means there is an SSL certificate, but it cannot be verified, which for example applies to self-signed certificates.
      • If that request fails as well, it means the site is entirely inaccessible over HTTPS.

The wp_is_https_supported() function simply looks at the https_detection_errors option controlled by the Cron hook, and it returns true if there are no errors stored.

One-click migration to HTTPS

A major pain point in migrating a WordPress site from HTTP to HTTPS has been the need to fix all the hard-coded URLs in existing database content which were still using the HTTP version, to avoid mixed content warnings. These URLs are usually migrated with a database replacement 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 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/, but that process is tedious and not intuitive to many WordPress administrators.

WordPress 5.7 introduces a new wp_replace_insecure_home_url() function which is hooked into various pieces of content to replace these insecure URLs on the fly. It relies on another new function wp_should_replace_insecure_home_url() which determines whether the URL replacement logic needs to run or not. All of the following conditions have to be fulfilled for the automatic content rewrites:

  • The site has to be using HTTPS, via wp_is_using_https().
  • A new internal flag option called https_migration_required has to be enabled. The option is automatically enabled when the “Site Address” and “WordPress Address” are switched to their HTTPS counterpart on a site with existing content. (In other words, a fresh_site that is immediately switched to HTTPS does not trigger the content rewrites logic.)
  • The “Site Address” and “WordPress Address” have to be using the same domain.

With the content rewriting of insecure URLs in place, the only change required to switch the site from HTTP to HTTPS is updating the “Site Address” and “WordPress Address” to their HTTPS counterparts. While this only entails updating two text input fields, it can still be simplified; this is why WordPress 5.7 includes another new function wp_update_urls_to_https() which updates both URLs accordingly. It also includes an extra check to verify that this resulted in WordPress correctly recognizing the site as using HTTPS; if not, the change automatically gets reverted to prevent any unexpected issues.

While the one-click migration introduced by WordPress 5.7 does not support advanced site configurations where e.g. “Site Address” and “WordPress Address” differ, it drastically simplifies migration in the common scenario; furthermore, the advanced configurations are often used by more technically savvy users that already know how to migrate to HTTPS anyway.

Administrators that would like to actually replace the URLs in the database can still do so. In that scenario, it is recommended to delete the https_migration_required option, to avoid the URL rewriting logic from running unnecessarily. Alternatively, the URL rewriting function can be unhooked entirely as follows:

remove_filter( 'the_content', 'wp_replace_insecure_home_url' );
remove_filter( 'the_excerpt', 'wp_replace_insecure_home_url' );
remove_filter( 'widget_text_content', 'wp_replace_insecure_home_url' );
remove_filter( 'wp_get_custom_css', 'wp_replace_insecure_home_url' );

Improved Site Health guidance

The HTTPS Status section in Site Health has been improved to guide the user more towards using HTTPS. If the environment already supports HTTPS (via wp_is_https_supported()), the UIUI User interface will now include a button to switch both site URLs with a single click (using wp_update_urls_to_https()). Users will need to have a new update_https 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. capability in order to perform the switch; by default this capability is granted to every user that can both manage_options and update_core.

HTTPS Status section when HTTPS is not yet supported by the environment
HTTPS Status section when HTTPS is already supported by the environment

Various minor improvements have been made to more accurately describe the site’s configuration. For example, sites that rely on the WP_HOME or WP_SITEURL constant will see this reflected now, since that means WordPress cannot automatically update these URLs.

The severityseverity The seriousness of the ticket in the eyes of the reporter. Generally, severity is a judgment of how bad a bug is, while priority is its relationship to other bugs. of not using HTTPS in the overall HTTPS Status Site Health test is now set to “critical”, whereas before it was “recommended”. This means that sites which do not use HTTPS will now see the “Should be improved” state in the Site Health dashboard 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., highlighting this further.

Providing custom support URLs for switching to HTTPS

In order to further help to guide WordPress administrators towards the switch to HTTPS, hosting providers that have their own support content for how to switch to HTTPS can now provide these URLs to WordPress so that users can get to that guidance directly from their administration panel.

  • Hosts which offer their own dedicated HTTPS support content can provide the URL that by setting a WP_UPDATE_HTTPS_URL environment variable or by hooking into a new wp_update_https_url 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.. If no such URL is provided, the default URL links to this HTTPS support article.
  • Hosts which offer a utility to automatically switch the site to HTTPS can provide the URL to do so by setting a WP_DIRECT_UPDATE_HTTPS_URL environment variable or by hooking into a new wp_direct_update_https_url filter. If no such URL is provided, the default URL triggers the aforementioned WordPress one-click mechanism.

For reference, see TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. tickets #47577 about HTTPS detection and #51437 about HTTPS migration.

Props to @timothyblynjacobs for proofreading

#5-7, #dev-notes, #https, #site-health

Send reset password links in WordPress 5.7

WordPress 5.7 introduces a new feature that allows website administrators to manually send a reset password link to existing users. This can be helpful when users lose their password and cannot use the lost password link for any reason.

In terms of workflow, the feature does not directly change the user’s password. It sends them a password reset link via email so they are able to reset their password by themselves. Sending a reset password link is more secure than directly changing the password for the user. Passwords should not be communicated directly.

The reset password email notification is sent using the existing retrieve_password() function, which can be filtered using the retrieve_password hook. Please note that retrieve_password was also moved from wp-login.php to wp-includes/user.php.

This feature can be found in several places in the WordPress Adminadmin (and super admin).

Using the user profile screen

The feature is available on the user profile screen, right above the “Set new password” setting.

Using the action link available on the users list screen

There is also a quick action link available in the users list. It is showed when you hover/focus the user’s row.

Using bulk actions

It is also possible to bulk send password reset links by using the bulk action available in the action dropdown located right above the users list table.

Password reset link email notification

Here is the content of the email notification:

Subject: [SITENAME] Password Reset
- - -

Someone has requested a password reset for the following account:

Site Name: [SITENAME]

Username: [USERNAME]

If this was a mistake, ignore this email and nothing will happen.

To reset your password, visit the following address:

[RESET_PASSWORD_URL]

This password reset request originated from the IP address [IPADDRESS].

The email subject and message can be filtered using the retrieve_password_title and the retrieve_password_message 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 reference, see ticketticket Created for both bug reports and feature development on the bug tracker. #34281

Props to @chaton666 and @jdy68 for proofreading

#5-7, #dev-notes

Robots API and max-image-preview directive in WordPress 5.7

WordPress 5.7 introduces a 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.-based Robots 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., providing central control over the robots 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. 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.). It furthermore adds a max-image-preview:large directive to the tag by default.

The robots meta tag lets you utilize a granular, page-specific approach to controlling how an individual page should be indexed and served to users in search engine results. This meta tag is commonly placed in the <head> section of a given page:

<!DOCTYPE html>
<html>
	<head>
		<meta name="robots" content="max-image-preview:large" />
	</head>

The max-image-preview:large directive allows search engines to display large image previews for the site resulting in an enhanced user experience. The directive is now added by default to sites that wish to be indexed by search engines.

wp_robots() new function

WP 5.7 introduces a wp_robots() function which outputs a robots meta tag. The function is automatically integrated with the relevant areas in WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., for example it is added to wp_head so that the robots meta tag is available in the frontend. Plugins and themes should not typically call this function manually; for special cases though, e.g. a custom frontend template that does not use wp_head(), the new function can be hooked into a custom filter:

add_action( 'my_custom_template_head', 'wp_robots' );

How to hook into the Robots API

The robots meta tag attributes can be filtered using the wp_robots hook. The wp_robots() function is entirely filter-based, so if no filter is added to wp_robots, no directives will be present, and therefore the entire robots meta tag will be omitted.

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 add their own robots meta tags are encouraged to switch to using the new Robots API, hooking their custom directives into the wp_robots filter.

Default robots meta tag values

As mentioned above, the robots meta tag is now included by default in wp_head as follows for WordPress sites that wish to be indexed by search engines:

<meta name="robots" content="max-image-preview:large" />

Developers can disable this directive using the following PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher snippet:

remove_filter( 'wp_robots', 'wp_robots_max_image_preview_large' );

The Robots API is also used to generate robots meta tags on some specific screens, with the following values:

  • When the “Discourage search engines from indexing this site” setting is enabled, the front end includes a noindex,nofollow directive in the Robots meta tag, as in previous versions. In this case, the max-image-preview:large directive is not added.
  • Within the 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. preview, the site includes a noindex directive in the Robots meta tag, as in previous versions.
  • The WordPress login page (wp-activate.php) includes a noindex,noarchive directive in the Robots meta tag, as well as a <meta name="referrer" content="strict-origin-when-cross-origin" /> tag, as in previous versions.
  • In multisitemultisite Used to describe a WordPress installation with a network of multiple blogs, grouped by sites. This installation type has shared users tables, and creates separate database tables for each blog (wp_posts becomes wp_0_posts). See also network, blog, site, the site activation page (wp-activate.php), where a newly registered user can confirm their newly created site, includes a noindex,noarchive directive in the Robots meta tag, as well as a <meta name="referrer" content="strict-origin-when-cross-origin" /> tag, as in previous versions.

Add custom values to robots meta tag

The wp_robots filter takes an array of key-value pairs. To add custom values to the robots meta tag, use the following filter:

function wporg_wp_robots_add_follow( $robots ) {
	$robots['follow'] = true;
	return $robots;
}
add_filter( 'wp_robots', 'wporg_wp_robots_add_follow' );

It will add the follow value in addition to any existing values. Given the max-image-preview:large is already added by default, this snippet will generate the following:

<meta name="robots" content="max-image-preview:large, follow" />

It’s also possible to unset existing values:

function wporg_wp_robots_add_follow( $robots ) {
	unset( $robots['max-image-preview'] );
	$robots['follow'] = true;
	return $robots;
}
add_filter( 'wp_robots', 'wporg_wp_robots_add_follow' );

Deprecated functions

The new Robots API controlled via the wp_robots filter replaces various separately injected robots meta tags that WordPress core used to conditionally provide. As such, the following functions have been deprecated and should no longer be used:

  • noindex(); instead, the new wp_robots_noindex() function can be hooked into the wp_robots filter.
  • wp_no_robots(); instead, the new wp_robots_no_robots() function can be hooked into the wp_robots filter.
  • wp_sensitive_page_meta(); this function placed two tags, so it has two separate replacements:
    • For the noindex,noarchive robots directive, the new wp_robots_sensitive_page() function can be hooked into the wp_robots filter.
    • For the extra referrer tag, the new wp_strict_cross_origin_referrer() function can be called.

For reference, see 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. #51511

Props to @davidbaumwald, @flixos90, and @tweetythierry for proofreading

#5-7, #dev-notes

Lazy-loading iframes in 5.7

In WordPress 5.7, iframes will be lazy-loaded by default, using the browser-level loading attribute. This will bring to iframes the same performance benefits which WordPress 5.5 introduced by lazy-loading images.

Similar to how it affects images, WordPress will add loading="lazy" to only those iframe tags that have both width and height attributes present, to avoid any perceived negative impact on layout shifting. The attribute is added on page output using the wp_filter_content_tags() function which was introduced in WordPress 5.5 with specifically that extensibility in mind which now allows reusing it for this new performance feature. Since the considerations of lazy-loading iframes are similar to those of lazy-loading images, please refer to the original image lazy-loading announcement post as well as this article on browser-level lazy-loading for background information on the topic.

See also #50756 for the ticketticket Created for both bug reports and feature development on the bug tracker. where this feature was worked on.

Impact on oEmbed content

By default, WordPress will add a loading="lazy" attribute to the following iframes:

  • iframes within post content (the_content)
  • iframes within post excerpts (the_excerpt)
  • iframes within text widgets (widget_text_content)

The majority of iframes used on WordPress sites typically come from its oEmbed integration, which will automatically transform a URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org to certain web platform resources (such as tweets or YouTube videos) into the referenced embedded media when pasted into the editor.

The markup of those iframe tags is controlled by the respective web service, and only some of those web services follow the best practice of providing width and height attribute. Since WordPress cannot guess the dimensions of the embedded resource, the loading="lazy" attribute will only be added if the oEmbed iframe 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.) comes with both dimension attributes present.

Customizing lazy-loading iframes

Developers can customize whether and how iframes are lazy-loaded in a similar way to how they can for images, with the primary 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. being the existing wp_lazy_loading_enabled, which going forward will return true for iframe tags by default.

For example, if you would like to turn off lazy-loading by default for iframes within post content, you could use the following code snippet:

function disable_post_content_iframe_lazy_loading( $default, $tag_name, $context ) {
	if ( 'iframe' === $tag_name && 'the_content' === $context ) {
		return false;
	}
	return $default;
}
add_filter(
	'wp_lazy_loading_enabled',
	'disable_post_content_iframe_lazy_loading',
	10,
	3
);

In addition, there is a new wp_iframe_tag_add_loading_attr filter which allows customization of a specific iframe tag. For example, you could use this filter to skip addition of the loading attribute on an iframeiframe iFrame is an acronym for an inline frame. An iFrame is used inside a webpage to load another HTML document and render it. This HTML document may also contain JavaScript and/or CSS which is loaded at the time when iframe tag is parsed by the user’s browser. that will likely appear within the initially visible viewport, to avoid impacting the Largest Contentful Paint metric. The filter has the same signature as the related wp_img_tag_add_loading_attr filter for images.

Here is an example code snippet which would disable lazy-loading iframes that embed YouTube videos within post content:

function skip_loading_lazy_youtube_iframes( $value, $iframe, $context ) {
	if ( 'the_content' === $context && false !== strpos( $iframe, 'youtube.com' ) ) {
		return false;
	}
	return $value;
}
add_filter(
	'wp_iframe_tag_add_loading_attr',
	'skip_loading_lazy_youtube_iframes',
	10,
	3
);

Please refer to the “Customizing lazy-loading” section of the image lazy-loading announcement post for additional guidance.

Props @audrasjb for proofreading.

#5-7, #dev-notes, #feature-lazyloading

Introducing additional functions to check if a post is publicly viewable in WordPress 5.7

WordPress 5.7 introduces two additional functions to check if a post is publicly viewable.

Previously, the is_post_type_viewable() function was already available to determine if a post type is visible to anonymous users via the publicly_queryable setting when registering the post type. However, it wasn’t sufficient to determine if a specific post is viewable as this function only checks for general post type settings.

That’s why WordPress 5.7 introduces is_post_status_viewable() function, which allows developers to determine whether a post status is publicly viewable or not. Internal and protected statuses are never considered viewable. For built in posts statuses the public attribute is checked, for custom statuses the publicly_queryable attribute is checked.

This function accepts one parameter:

  • $post_status: The post status name or object. This parameter is required.

Usage example:

<?php
global $post;
$current_post_status = get_post_status( $post );
if ( is_post_status_viewable( $current_post_status ) ) {
	echo 'This post uses a public post status';
} else {
	echo 'This post uses a non public post status';
}

Please note that password protected posts are considered publicly viewable, while private posts are not.

WordPress 5.7 also introduces is_post_publicly_viewable() for determining if an individual post can be viewed by logged out users. A post is considered viewable if both is_post_status_viewable() and is_post_type_viewable() return true for the post’s attributes.

This function accepts one parameter:

  • $post: A post ID or a post object. This parameter is optional. By default it passes the global $post object.

Usage example:

<?php
if ( is_post_publicly_viewable() ) {
	echo 'This post is publicly viewable';
} else {
	echo 'This post is not publicly viewable';
}

Additionally, the is_post_type_viewable() function was modified to return false if an unregistered post type is passed to the function to avoid attempting to access properties on a non-object.


For reference, see ticketticket Created for both bug reports and feature development on the bug tracker. #49380

Props @peterwilsoncc for proofreading

#5-7, #dev-notes

WordPress 5.7: A new dynamic hook to filter the content of a single block

The render_block() function is responsible for rendering each individual 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. into an HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. string. There are several filters available that allow plugins and themes to alter how the block is rendered.

  • pre_render_block: Allows render_block() to be short-circuited, by returning a non-null value.
  • render_block_data: Filters the block being rendered in render_block(), before it’s processed.
  • render_block_context: Filters the default context provided to a rendered block.
  • render_block: Filters the content of a single block.

While these filters grant a large amount of control over how an individual block is rendered, hooked functions need to perform some verification that the block being rendered is of the desired block type before making any modifications.

In WordPress 5.7, a new dynamic 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., render_block_{$this->name}, will be introduced, allowing a function to be hooked only to blocks of a specific type. In the new filter, {$this->name} represents the name or slug of the block as it was registered. For example, the paragraph block, registered with a name of core/paragraph can be filtered using render_block_core/paragraph.

This reduces the amount of code previously needed to target the rendering of specific block types.

Usage examples

The following example will filter all core/paragraph blocks, wrapping them in a <div> element.

/**
 * Wrap all core/paragragh blocks in a <div>.
 *
 * @param string $block_content The block content about to be appended.
 * @param array  $block         The full block, including name and attributes.
 * @return string Modified block content.
 */
function wporg_paragraph_block_wrapper( $block_content, $block ) {
	$content  = '<div class="my-custom-wrapper">' . $block_content . '</div>';
	return $content;
}
add_filter( 'render_block_core/paragraph', 'wporg_paragraph_block_wrapper', 10, 2 );

Result:

<div class="my-custom-wrapper">
	<!-- block content -->
</div>

Note: The names of all WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. block types are prefixed with core/. For custom block types declared in 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, the name of the filter may be something like render_block_my-plugin/my-custom-block.


In this example, only paragraphs using the large font size keyword will be wrapped into a <div> element:

/**
 * Wrap all core/paragraph blocks with large font size in a <div>.
 *
 * @param string $block_content The block content about to be appended.
 * @param array  $block         The full block, including name and attributes.
 * @return string Modified block content.
 */
function wporg_large_sized_paragraph_block_wrapper( $block_content, $block ) {
	if ( isset( $block['attrs']['fontSize'] ) && 'large' === $block['attrs']['fontSize'] ) {
		$block_content = '<div class="my-large-paragraph">' . $block_content . '</div>';
	}
	return $block_content;
}
add_filter( 'render_block_core/paragraph', 'wporg_large_sized_paragraph_block_wrapper', 10, 2 );

Result:

<div class="my-large-paragraph">
	<p class="has-large-font-size">
		<!-- block content -->
	</p>
</div>

For more information on this change, see ticketticket Created for both bug reports and feature development on the bug tracker. #46187 on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

Props @chaton666 and @desrosj for proofreading.

#5-7, #dev-notes

Login & registration screens changes in WordPress 5.7

This devnotedev 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. summarizes the changes related to the login and registration screens coming in WordPress 5.7.

Reset password screen user interface improvements

Previously, it was unclear that the displayed password is only being suggested and should be saved by clicking the Reset Password button. This change adds two separate “Generate Password” and “Save Password” buttons, for better clarity.

For reference, see ticketticket Created for both bug reports and feature development on the bug tracker. #39638.

A new hook to 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 user data object during a password reset request

WordPress 5.7 also introduces the new lostpassword_user_data filter which allows for the user data object during a password reset request to be filtered. For example, It allows developers to perform custom validation using data other than username or email address.

The $errors object is also passed to the filter so developers are able to know of any existing error. This can be used in conjunction with the lostpassword_errors filter to remove an error from the error object if necessary.

For reference, see ticket #51924.

Changes related to the existing retrieve_password function

As part of the new feature in 5.7 that allows an Administrator to send a user a password reset link, the retrieve_password() function was moved from wp-login.php to wp-includes/user.php.

In addition the $user_login parameter was added to this function, to make it easier to use the function independently from the login screen.

For reference, see changesets [50129] and [50140].

A new hook to filter the “Back to blogblog (versus network, site)” link

In WordPress 5.7, a new login_site_html_link hook was added to allow developers to adjust the “Go to site” link displayed in the login page footer.

The only parameter of this filter is $link, which contains the full HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. link to display. Using this filter, developers are allowed to entirely replace the HTML link.

Example of use:

function wporg_login_site_html_link( $link ) {
        return '<a href="' . esc_url( home_url( '/' ) ) . '">' . __( 'Back to the website', 'text-domain' ) . '</a>';
}
add_filter( 'login_site_html_link', 'wporg_login_site_html_link', 10, 1 );

For reference, see ticket #35449.


Thanks @chaton666 and @johnbillion for proofreading 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-7, #dev-notes

Introducing new Post Parent related functions in WordPress 5.7

Update: These functions were originally introduced as get_parent_post() and has_parent_post() but have since been renamed to get_post_parent() and has_post_parent().

In WordPress 5.7, two long awaited functions were added to determine if a post has a parent and to get the related parent Post object. These functions are quite simple to use. They reduce the logic needed in themes and plugins.

Before committing this change 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 repository was checked for existing plugins and themes that already use either of the two functions. No plugin or theme is affected in 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/ repository.

Kind reminder for WordPress developers: if you use the get_post_parent() or has_post_parent() functions in any custom plugin or theme, please prefix them ahead of WP 5.7 to avoid any PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher error.

For reference, this enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. has been addressed in ticketticket Created for both bug reports and feature development on the bug tracker. #33045.

New template 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.): get_post_parent()

This new template tag accepts one parameter: a post ID or a WP_Post object. By default it uses the global variable $post if available. It retrieves the parent WP_Post object for the given post.

New conditional tag: has_post_parent()

This new conditional tag accepts one parameter: a post ID or a WP_Post object. By default it uses global variable $post if available. It returns true if the post has a parent, false otherwise.

Basic example of use

These two functions can be combined to display a “Back to parent page” link:

<?php if ( has_post_parent( get_the_ID() ) ) : ?>
	<a href="<?php the_permalink( get_post_parent( get_the_ID() ) ); ?>">
		<?php
		echo esc_html( sprintf(
			__( 'Back to parent page: %s', 'text-domain' ),
			get_the_title( get_post_parent( get_the_ID() ) )
		) );
		?>
	</a>
<?php endif; ?>

Props @chaton666 and @johnbillion for proofreading 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-7, #dev-notes