New action wp_after_insert_post in WordPress 5.6.

The new action wp_after_insert_post has been added to WordPress 5.6 to allow theme and 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 to run custom code after a post and its terms and 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. data have been updated.

The save_post and related actions have commonly been used for this purpose but these 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. can fire before terms and meta data are updated outside of the classic editor. (For example in the REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/., via the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor, 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. and when an auto-draft is created.)

The new action sends up to four parameters:

  • $post_id The post ID has been updated, an integer.
  • $post The full post object in its updated form, a WP_Post object.
  • $updated Whether the post has been updated or not, a boolean.
  • $post_before The full post object prior to the update, a WP_Post object. For new posts this is null.

By default WordPress fires this hook at the end of wp_insert_post(). A third parameter has been added to the function to allow developers to prevent the hook from firing automatically:

  • $fire_after_hooks Whether to fire the after insert hooks, a boolean. Optional, default true.

The same parameter has been added to wp_update_post() as the third parameter and wp_insert_attachment() as the fifth parameter.

In the event a developer calls any of these functions and prevents the hook from firing, it is expected they will manually call the new function wp_after_insert_post() to trigger the new action. This new function requires three parameters:

  • $post The post ID or object that has been saved, ether an integer or WP_Post object
  • $update Whether the post has been updated (true) or inserted (false).
  • $post_before null for new posts, the WP_Post object prior to the update for updated posts.

For the history of this change, see ticketticket Created for both bug reports and feature development on the bug tracker. #45114. The changes were committed in [49172] and [49731]. A discussion on the approach took place in Slack during a dev chat.

An example when inserting a post.

In the event you are calling wp_insert_post() or one of the related functions listed above, if you are then updating the post’s terms or meta data separately it is recommended you prevent the hook from running and call it manually. For example:

$post_id = wp_insert_post(
    array(
        'post_title'   => 'My post title',
        'post_content' => 'My post content',
        'post_type'    => 'my_cpt',
    ),
    false,
    false
);

add_post_meta( $post_id, 'my_meta_key', 'my meta value' );

wp_after_insert_post( $post_id, false, null );

When updating a post, you will need to store the WP_Post object’s state before running the update. Due to the way PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher passes objects and the get_post() internals, it is recommended you get the post via its ID.

$before_post = get_post( $post_id );

wp_update_post(
    array(
        'ID'           => $post_id,
        'post_title'   => 'My updated post title',
        'post_content' => 'My updated post content',
    ),
    false,
    false
);

add_post_meta( $post_id, 'my_meta_key', 'my meta value' );

wp_after_insert_post( $post_id, true, $before_post );

Props to @planningwrite, @timothyblynjacobs and @chrisvanpatten for reviewing 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 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..

Edit: The $post_before parameters were committed after this dev note was first published. This has been updated to reflect those changes.

#5-6, #dev-notes

Dev Chat Summary: November 18 2020

Hello! Here’s what happened in the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. dev chat on Wednesday, November 18, 2020, 05:00 UTC and Wednesday, November 4, 2020, 20:00 UTC, following this agenda.

05:00 UTC core dev chat

@thewebprincess facilitated the meeting and took notes. Find the full Slack archive here.

20:00 UTC core dev chat

@thelmachido facilitated the meeting and @laurora took notes. The full Slack archive can be viewed here.

Both groups followed this agenda: https://make.wordpress.org/core/2020/11/04/dev-chat-agenda-october-4th-november-2020/

Announcements

RC1 of 5.6 has been released! The team would love you to help by testing the release candidaterelease candidate One of the final stages in the version release cycle, this version signals the potential to be a final release to the public. Also see alpha (beta)., and/or by offering any translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. skills. More information can be found in the Release Candidate post.

@helen shared that the theme previewer site [wp-themes.com] is now showing starter content for the demos for Twenty Twenty One, Twenty Twenty, and Twenty Seventeen, thanks to some help from @dinhtungdu and @dd32. Helen noted that it is not yet available for themes at large; the reasons for which she’ll be sharing in a post that’ll be published soon.

Highlighted Posts

A Week in Core – November 16, 2020

Site Health Check changes in 5.6

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 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. are starting to show up ready for final release, here’s the latest dev-notes 5.6

Updates from Component Maintainers/Focus Leads

General:
@sergeybiryukov shared that PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher 8 release is scheduled for November 26. For WordPress 5.6, the current plan is to declare it as “betaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. compatible with PHP 8”. A post on make/core is coming soon, but you can see the reasoning behind this in the following SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. conversations:
https://wordpress.slack.com/archives/C02RQBWTW/p1605646136362600
https://wordpress.slack.com/archives/C02RQBWTW/p1605646630372100

@desrosj added that the 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 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 this is almost complete, and will be added tomorrow [November 19].

Open Floor

@isabel_brison flagged that there are still a number of outstanding issues in relation to the editor. If you think you might be able to help out in clearing these, please take a look at the to-do column on the Gutenberg project board on GitHub.

@webcommsat shared that the Marketing Team is working on questions and answers for 5.6 for the HelpHub and working with the Training Team. The team will add the latest version to the Marketing Team GitHub at the end of this week, for those who are interested in helping with this.

@desrosj apologized for the delay in publishing the 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. – this will be published by the end of the week.

@francina has started recapping the comments to the post about aligning the WP release cycle to industry standards. Right now there are very few voices, and despite the deadline for feedback stated has now passed, she would still love to hear from more people. Please review the post and share your feedback.

@whyisjake asked when the planning for the 5.7 release cycle (team etc) is going to start. @francina suspects @chanthaboune has a plan, but stressed that it would be great to see 5.6 squad members back again, and encourages anyone who has any questions about being part of the release squad to reach out to her or @audrasjb. Francesca will be adding a list of release squad roles and more information on how you can get involved in the handbook soon.

Next Dev Chat meetings

The next meetings will take place on Wednesday, November 25, 2020, 05:00 UTC and Wednesday, November 25, 2020, 20:00 UTC in the #core Slack channel. Please feel free to drop in with any updates or questions.

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

Dev Chat Agenda: 18th November 2020:


Here is the #agenda for this week’s meetings happening at:
Wednesday, 18 November 2020, 0500UTC and Wednesday, 18November 2020, 2000UTC .

  • Announcements –
  • Highlighted blogblog (versus network, site) posts –
    • A Week in Core – November 16, 2020
    • Site Health Check changes in 5.6
    • 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 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. are starting to show up ready for final release, here’s the latest dev-notes 5.6
  • Calls from component maintainers and/or focus leads
  • Open Floor
    If you have something else you want to include to the agenda, please mention it in the comments below.

The #dev-chat meetings will be held on Wednesday, 18 November 2020, 05:00UTC and Wednesday, 18 November 2020, 2000UTC. These meetings are held in the #core channel. To join the meeting, you’ll need an account on the Making WordPress Slack .

#5-6, #agenda

New createBlocksFromInnerBlocksTemplate Block API

There is a new BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. 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. in WordPress 5.6: createBlocksFromInnerBlocksTemplate, with which you can create blocks from InnerBlocks template.

Given an array of InnerBlocks templates or Block Objects, it returns an array of created Blocks from them.
It handles the case of having InnerBlocks as Blocks by converting them to the proper format to continue recursively.

This is especially useful for handling block variations, transformations and creation/replacement of blocks which use InnerBlocks template.

An example that would create new blocks from a block variation using InnerBlocks’ template and replace the block’s content is:

import { InnerBlocks } from '@wordpress/block-editor';
import { useDispatch } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { Button, ToolbarGroup, ToolbarButton } from '@wordpress/components';
import { BlockControls, useBlockProps } from '@wordpress/block-editor';
import { createBlocksFromInnerBlocksTemplate } from '@wordpress/blocks';

function MyEditBlock( { clientId } ) {
    const { replaceInnerBlocks } = useDispatch( 'core/block-editor' );
    const variation = {
        name: 'my-variation',
        title: __( 'My variation' ),
        innerBlocks: [
            [ 'core/paragraph', { content: 'Hello' } ],
            [ 'core/paragraph', { placeholder: __( 'Write title…' ) } ],
        ],
    };
    const onClick = () => {
        replaceInnerBlocks(
            clientId,
            createBlocksFromInnerBlocksTemplate( variation.innerBlocks )
        );
    };
    return (
        <div { ...useBlockProps() }>
            <BlockControls>
                <ToolbarGroup>
                    <ToolbarButton onClick={ onClick }>
                        <span>Change InnerBlocks</span>
                    </ToolbarButton>
                </ToolbarGroup>
            </BlockControls>
            <InnerBlocks />
        </div>
    );
}

See the pull request for implementation details and more.

Props to @ntsekouras for writing 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 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-6, #block-editor, #dev-notes

Changes to Toolbar components in WordPress 5.6

Toolbar shouldn’t be used within other toolbars

To better reflect its semantics, the Toolbar component shouldn’t be used to group a set of toolbar controls within another toolbar anymore and will show a deprecation warning if used like so. ToolbarGroup should be used instead.

Before

<BlockControls>
  <Toolbar>
    <ToolbarButton />
  </Toolbar>
</BlockControls>

After

<BlockControls>
  <ToolbarGroup>
    <ToolbarButton />
  </ToolbarGroup>
</BlockControls>

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. toolbars now require controls to be ToolbarButton or ToolbarItem elements

Rendering native <button> or other custom tabbable elements directly as toolbar items (for example, using BlockControls or BlockFormatControls) has been deprecated. In order to improve toolbar accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility), toolbar items now should use ToolbarButton for regular buttons, or ToolbarItem for any other kind of control (for example, dropdowns).

Before

<BlockControls>
  <button />
  <Button />
  <DropdownMenu />
</BlockControls>

After

<BlockControls>
  <ToolbarItem as="button" />
  <ToolbarButton />
  <ToolbarItem>
    { ( itemProps ) => ( <DropdownMenu toggleProps={ itemProps } /> ) }
  </ToolbarItem>
</BlockControls>

Props to @hazdiego for writing 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 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-6, #block-editor, #dev-notes

Editor styling changes in WordPress 5.6

These changes are important enhancements for both accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) and user experience on small screens.

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. styles use relative instead of absolute values

Previously, blocks were using hardcoded pixel values for all their sizing properties (paddings, margins, font-sizes etc).

Starting with WordPress 5.6, default block-styles use font-size-relative units (em) making it easier for themes to change the default content font-size without having to rewrite/override all block styles.

Media & Text blocks show media on top in mobile view

Previously, if the stack on mobile behavior was not disabled, and media had the option to appear on the left (the default), on mobile, the media appeared on top and the text on the bottom. If media had the option to appear on the right on mobile when stacked media would appear at the bottom and text on top.

There was feedback that the left/right position of media should not map to top/bottom on mobile and that for a better UXUX User experience on mobile, media should always appear on top. Starting with WordPress, 5.6 media text blocks will have media on top on mobile unless the stack on mobile option is disabled, and in that case, media appears at the side of text like on desktop.

Props to @aristath and @jorgefilipecosta for writing these 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 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-6, #block-editor, #dev-notes

Reusable Blocks extracted into a separate package

Reusable blocks are a feature available in the post editor. They were previously part of the @wordpress/editor package. To make them available in other editors, they have been moved to a separate package called @wordpress/reusable-blocks.

How it works

To enable reusable blocks in your blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. editor, simply change your <BlockEditorProvider /> as follows:

import { ReusableBlocksMenuItems } from '@wordpress/reusable-blocks';

const { __experimentalReusableBlocks } = useSelect(
    ( select ) => select( 'core' ).getEntityRecords(
        'postType',
        'wp_block',
    )
);

return (
    <BlockEditorProvider
        settings={ {
            ...settings,
            __experimentalReusableBlocks,
        } }
        { ...props } // value, onInput, onChange, etc.
    >
        <ReusableBlocksMenuItems />
        { children }
    </BlockEditorProvider>
);

Props to @zieladam for writing 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 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-6, #block-editor, #dev-notes

Block Supports In WordPress 5.6

Several coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. and third party blocks share different customization tools. Things like color, background, font size, alignment and others are customizations options 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. authors are likely to add to their own block. To increase the consistency and also make it easier to introduce these options into their blocks, block authors can use the Block supports APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways.. WordPress 5.6 will see the introduction of a number of new block supports and allows dynamic blocks to use them as well.

Blocks can declare support for style properties

To enable the new block supports, add the desired keys to the “supports” property of the block.json file or directly into the registerBlockType function. The block editor will automatically show a UIUI User interface control for the user to set those values.

supports: {
    color: {
        background: true, // Enable background color UI control.
        gradient: true, // Enable gradient color UI control.
        text: true // Enable text color UI control.
    },
    fontSize: true, // Enable font size UI control.
    lineHeight: true // Enable line height UI control.
}

For some of these properties, the active theme may need to opt-in for them to be enabled. That’s the case of lineHeight, for example.

How it works

When the user interacts with the controls, they will automatically attach the style value to the wrapper element of the block. This works as it did before:

  • If the control offers some preset values and the user selects one of them, a class will be attached with the name .has-<value>-<preset-category> (i.e.: has-normal-font-size).
  • If the user selects a custom value, it’ll be attached as part of the style attribute of the wrapper.

Note that these are attached to the wrapper element of the block, so it works best with blocks that follow the newest apiVersion (see related dev note).

The UI controls that present users with a set of preset values, take them from the corresponding theme supports:

Dynamic blocks support

You can also use the block supports in dynamic blocks by making sure the config is added to the register_block_type server side (or the block.jsonJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.) and by rendering the block wrapper attributes in your block’s render callback function:

function my_block_render_callback_function( $attributes ) {
    $wrapper_attributes = get_block_wrapper_attributes();
    $content_markup = "something";
    return sprintf(
        '<div %1$s>%2$s</div>',
        $wrapper_attributes,
        $content_markup
    );
}

In depth

When blocks declare support for a style property, they also gain additional block attributes. These can also be used to set default values:

attributes: {
    backgroundColor: {
        type: 'string',
        default: 'value',
    },
    gradient: {
        type: 'string',
        default: 'value',
    },
    textColor: {
        type: 'string',
        default: 'value',
    },
    fontSize: {
        type: 'string',
        default: 'value'
    },
    style: {
        type: 'Object',
        default: {
            color: {
                background: 'value',
                gradient: 'value',
                link: 'value',
                text: 'value'
            },
            typography: {
                fontSize: 'value',
                lineHeight: 'value',
            }
        }
    }
}

The attributes backgroundColor, gradient, textColor, and fontSize hold any preset values the user has selected. When the user sets a custom value instead, these are stored in the corresponding key within the style attribute. Check out the documentation for more details.

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

Block API version 2

WordPress 5.6 will come with a new BlockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. 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. version, enabling blocks to render their own block wrapper element. This is part of a larger effort to lighten the editor content’s DOM tree so that it matches the saved content (and therefore the front-end of the site). The biggest benefit of this is that themes and plugins can more easily style the block content if the markup is the same in the editor.

Enabling API version 2

To use the new API, you must opt-in to to API version 2. If you opt-in to API version 2, you must also render your own block wrapper element with the new API. To opt-in, set the apiVersion property to 2 on the block configuration object.

registerBlockType( name, { apiVersion: 2 } );

useBlockProps

When using API version 2, you must use the new useBlockProps hook in the block’s edit function to mark the block’s wrapper element. The hook will insert attributes and event handlers needed to enable block behaviour. Any attributes you wish to pass to the block element must be passed through useBlockProps and the returned value be spread onto the element.

import { useBlockProps } from '@wordpress/block-editor';

function Edit( { attributes } ) {
    const blockProps = useBlockProps( {
        className: someClassName,
        style: { color: 'blue' },
    } );
    return <p { ...blockProps }>{ attributes.content }</p>;
}

If you wish to use the element ref, you can pass one to useBlockProps.

import { useBlockProps } from '@wordpress/block-editor';

function Edit( { attributes } ) {
    const ref = useRef();
    const blockProps = useBlockProps( { ref } );
    return <p { ...blockProps }>{ attributes.content }</p>;
}

The save function must also use the save equivalent of the hook, useBlockProps.save.

import { useBlockProps } from '@wordpress/block-editor';

function Save( { attributes } ) {
    const blockProps = useBlockProps.save( {
        className: someClassName,
        style: { color: 'blue' },
    } );
    return <p { ...blockProps }>{ attributes.content }</p>;
}

Supporting both versions

If you use API version 2, it is recommended to set the Requires at least  header field to 5.6 so 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 only updates after WordPress updates to 5.6. If users use an older version of WordPress, they would sensibly also use an older version of your plugin, hopefully encouraging them to update WordPress. It’s possible to do security fixes by releasing patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. versions for the older plugin versions, in case that is a concern.

If you really wish to support both API versions, you will need to register a different edit and save function for the previous version, either by loading a different block registration file entirely, or by passing the WordPress version number to 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/. on the front-end and conditionally setting the edit and save function at the time of block registration.

API version 1

The block wrapper element is added by the framework with the contents of Edit inside of it.

function Edit( { attributes } ) {
    return (
        <p className={ someClassName } style={ { color: 'blue' } }>
            { attributes.content }
        </p>
    );
}

API version 2

The block wrapper element must be marked by the Edit component with the useBlockProps hook.

import { useBlockProps } from '@wordpress/block-editor';

function Edit( { attributes } ) {
    const blockProps = useBlockProps( {
        className: someClassName,
        style: { color: 'blue' },
    } );
    return <p { ...blockProps }>{ attributes.content }</p>;
}

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

Site Health Check changes in 5.6

With the release of WordPress 5.6, enhancements have been made to the way the Site Health component handles, and validates, health checks.

Site Health check data validation

First up is #50145. It adds validation rules to the response form for an asynchronous site-health check.

Prior to this patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing., any 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. asynchronous response would cause a fatal 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/. error, halting further processing of checks, and preventing the top of the page indicator from ever reaching a finished state.

An invalid response will now just be discarded with the introduction of this data format validator. It will not count towards the Site Health indicator or be listed among the checks.

(Oh, and you’re no longer required to add a badge to your checks. It’s useful, but not a hard requirement).

Asynchronous health checks via REST endpoints

With ticketticket Created for both bug reports and feature development on the bug tracker. #48105, we see Site Health moving away from admin-ajax.php for its asynchronous tests towards a dedicated REST APIREST API The REST API is an acronym for the RESTful Application Program Interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application (think “phone app” or “website”) can communicate with the data store (think “database” or “file system”) https://developer.wordpress.org/rest-api/. endpoint.

Starting in WordPress 5.6, asynchronous tests can be found under the /wp-json/wp-site-health/v1 namespace.

This also opens it up for plugins and themes to utilize REST endpoints, and not just ajax actions, for their tests. To maintain backwards compatibility, each test can now declare has_rest (defaults to false). If this is of a true value, then the test argument is treated as an absolute URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org (this means that it should be a fully qualified address, and not a relative one), for example, by using the rest_url() function provided by coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..

The reason for using an absolute URL, over a relative one, is to give developers flexibility so they may have an external service where it makes sense to do a remote request.

Scheduled Site Health checks

Since asynchronous calls were less than ideal to query from a scheduled event when run locally, #48105 and #51547 introduce the async_direct_test argument to a test array. This argument should be a callable instance of your test, that can be run directly, without an asynchronous call.

Asynchronous calls were implemented to prevent slow tests from preventing page loads and timeouts. Such concerns do not exist in the context of a scheduled event.

You still register your tests (or remove ones that are not needed in your scenario) using the site_status_tests 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. in a way similar to this:

class My_Custom_Feature {

	/**
	 * Set up class.
	 */
	public function __construct() {
		add_filter( 'site_status_tests', array( $this, 'site_tests' ) );
		
		add_action( 'rest_api_init', array( $this, 'register_rest_route' ) );
	}
	
	/**
	 * Register rest routes.
	 */
	public function register_rest_route() {
		register_rest_route(
			'my-custom-feature/v1',
			'/test/is-working',
			array(
				array(
					'methods'             => 'GET',
					'callback'            => array( $this, 'run_test' ),
					'permission_callback' => function() {
						// Perform any capability checks or similar here.
						return current_user_can( 'view_site_health_checks' );
					},
				),
			)
		);
	}
	
	/**
	 * Filter Site health tests to add our custom test.
	 * 
	 * @param array $tests An associated array of existing tests.
	 * @return array An array of available tests.
	 */
	public function site_tests( $tests ) {
		$tests['async']['my-custom-feature'] = array(
			'label'             => __( 'My feature label', 'my-feature' ),
			'test'              => rest_url( 'my-custom-feature/v1/test/is-working' ),
			'has_rest'          => true,
			'async_direct_test' => array( $this, 'run_test' ),
		);
	
		return $tests;
	}
	
	/**
	 * Run our test to check if the test is reachable.
	 *
	 * @return array An associated array of test result details.
	 */
	public function run_test() {
		$result = array(
			'label'       => __( 'My custom function test', 'my-feature' ),
			'status'      => 'good',
			'description' => __( 'The callback to this test worked', 'my-feature' ),
			'test'        => 'my-custom-feature',
		);
		
		return $result;
	}
}

// Initiate custom function.
new My_Custom_Feature;

The above example registers a custom rest route with a direct test callback. Additionally, it adds to the array of asynchronous tests available to the Site Health component.

When a check is performed, the result will be a passing test saying the test is reachable. If the check is run during a scheduled event, the test will not use the REST API endpoint. Instead, it will call the test directly.

The REST API handling also added improved checks for 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. failure states (previously it looked for an instance of WP_Error, which is not returned in the case of a REST API error), and better listing of asynchronous tests that fail for the site user. It now informs the site user of any failures that have an error state.

Props @planningwrite for copy-edits and proofreading.

#5-6, #dev-notes