External Library updates in WordPress 5.5: call for testing

Edit 7/1/20: The post initially indicated that a minified version of Moment.js was now included in CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. This was incorrect, a minified version has always been included, but as a direct copy from upstream. That copy now has a sourceMappingURL reference (which is not desired). For that reason, the library is now minified in the Core build process instead. That sentence was removed to prevent confusion. Props @sergeybiryukov for catching that.

Edit 7/2/20: After this note was published, new versions of the Moment.js and getID3 libraries were committed. The version updates for each have been adjusted appropriately.


WordPress 5.5 is currently slated to bring some long awaited updates to a handful of external libraries bundled with Core. A few of the updates are particularly large, and while backwards compatibility measures were taken, they could potentially require adjustments to plugins, themes, and custom code. For that reason, this developer note also doubles as a call for testing.

Please help test these library updates, and report back any bugs to help ensure that no edge cases were missed during the initial testing.

You can test these changes by installing the WordPress Beta Tester 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 (choose the “bleeding edgebleeding edge The latest revision of the software, generally in development and often unstable. Also known as trunk. nightlies” option), or download the nightly package directly (regenerated from trunk daily).


Remember, running the nightly version of WordPress is not recommended for production environments. Consider setting up a local development environment to test instead.


A full list of External Library tickets can be found on Trac, but below are the library updates currently slated to ship with WordPress 5.5, including all of the details you need to be aware of. The libraries that require an extra keen attention to detail are marked “please test”.

PHPMailer (please test)

Because of conflicting PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 support policies (support for PHP < 5.5 in was dropped in newer versions of the PHPMailer library), WordPress Core has been stuck on the 5.x version of PHPMailer for quite some time, even though a newer, 6.x version exists. However, now that WordPress only officially supports PHP back to version 5.6.20, PHPMailer can finally be updated.

This is a major update to the library. Please help by testing this update to ensure any edge cases are discovered.

Plugins that appear to be utilizing the library will soon receive an email to test their code. Below is what you need to know about the changes as they relate to WordPress Core.

Note: this is not an exhaustive list. For a more complete list of changes, please consult the Upgrading from PHPMailer 5.2 to 6.0 guide.

New file locations

To makemake A collection of P2 blogs at make.wordpress.org, which are the home to a number of contributor groups, including core development (make/core, formerly "wpdevel"), the UI working group (make/ui), translators (make/polyglots), the theme reviewers (make/themes), resources for plugin authors (make/plugins), and the accessibility working group (make/accessibility). updating the library easier, the PHPMailer files have been moved into the wp-includes/PHPMailer directory. The old files will remain for backwards compatibility and load the new corresponding files, but loading them will now throw a _deprecated_file() warning.

  • wp-includes/class-phpmailer.php is replaced by wp-includes/PHPMailer/PHPMailer.php.
  • wp-includes/class-smtp.php is replaced by wp-includes/PHPMailer/SMTP.php.

Additionally, the phpmailerException class is now separated into its own file, wp-includes/PHPMailer/Exception.php (previously, it was included at the bottom of the class-phpmailer.php file). When loading the PHPMailer library, the Exception.php file is required, and should also be loaded. If the old class-phpmailer.php file is loaded, the exception class will be loaded automatically to minimize failures.

New PHPMailer namespace

In past versions, the PHPMailer class existed within the global space. However, moving forward, the PHPMailer library is under the new PHPMailer\PHPMailer namespace. Below is an example of the old usage, and an example of the new way to utilize the library.

Old method

<?php
require_once ABSPATH . WPINC . '/class-phpmailer.php;
$phpmailer_instance = new PHPMailer();

New methods

Both examples will produce identical results.

<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php;
require_once ABSPATH . WPINC . '/PHPMailer/Exception.php;
$phpmailer_instance = new PHPMailer();
<?php
require_once ABSPATH . WPINC . '/PHPMailer/PHPMailer.php;
require_once ABSPATH . WPINC . '/PHPMailer/Exception.php;
$phpmailer_instance = new PHPMailer\PHPMailer\PHPMailer();

Similar changes must also be made when utilizing the PHPMailer Exception class.

The old classes have been registered as aliases of the new, properly namespaced classes using class_alias() in PHP (this is true for the PHPMailer, phpmailerException and SMTP classes). This means that a plugin containing code similar to the “old method” will continue to work seamlessly until it can be updated (with the exception of the _deprecated_file() notice).

Note: the aliases will only exist if the old, deprecated files are included. A plugin relying on Core to load the PHPMailer library will not have an alias present as the new files are now loaded instead.

Deprecated elements have been removed

Another big change in the 6.x update was the removal of all deprecated properties and methods. A full list of removed elements can be found in the upgrade guide.

Plugins using PHPMailer

All plugins that appear to be utilizing PHPMailer will soon be receiving an email notification to test their code and make any necessary adjustments.


For more information, check out the full list of changes included with this update, the PHPMailer 6.0 upgrade guide, or the related TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. tickets (#41750, #50379, #50380).

SimplePie (please test)

SimplePie is a RSS and Atom feed framework bundled with WordPress Core to handle the consumption of RSS and Atom feeds. The library has remained largely untouched for several years, but has been updated from version 1.3.1 to the latest version (1.5.5) for WordPress 5.5.

This update includes bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. fixes, compatibility fixes for newer versions of PHP, added support for additional date formats, and minor improvements to ensure that feeds continue to be parsed correctly. Support for caching feed data to Redis and Memcached has also been added.

It is highly recommended that you test your code if your sitesite (versus network, blog) fetches and processes RSS/Atom feeds.

Plugin authors were previously notified to test their code against the 1.5.5 update in early May, and the authors of plugins that were identified as using SimplePie should have received an additional follow up email. While no issues have been reported so far, it’s still possible that there may be undiscovered edge cases.

For more information, check out the full list of changes in SimplePie 1.3.1 to 1.5.5, or the related Trac ticketticket Created for both bug reports and feature development on the bug tracker. (#36669).

Twemoji

Earlier this year, the Unicode Consortium announced that Emoji v13.0 had been finalized. In addition to the 62 brand new emojis that were added, 55 gender and skin-tone variants were also added.

Platforms will begin rolling out native support later this year. But why wait? The Twemoji library has already been updated to support the new emojis, and that update will be included in WordPress 5.5.

So start spicing up your blogblog (versus network, site) about ninja (🥷) techniques, using tamales (🫔) and olives (🫒) on your food blog, and beavers (🦫) or polar bears (🐻‍❄️) on your wildlife blog.

For more information, check out the full list of new emojis added in Emoji v13.0, the Twemoji 13.0 release notes, or the corresponding ticket on Trac (#50148).

Masonry & imagesLoaded

The Masonry library has been updated from version v3.3.2 to 4.2.2, and the related imagesLoaded library has been updated from v3.2.0 to v4.1.4.

The biggest change in this update is the removal of support for IE versions 8 & 9. Core has not supported these versions of IE since WordPress 4.8, but if supporting these versions of Internet Explorer is important to your user base, please explore enqueuing your own versions of these libraries instead.

For more information, check out the full list of changes in Masonry, the full list of changes in imagesLoaded, or the related Trac ticket (#37675).

getID3

The getID3 library has been updated from version v1.9.18 to v1.9.20. This is a minor update that fixed several bugs. These fixes included one that caused a PHP notice when using PHP 7.4 and processing MP3 audio files.

For more information, check out the full list of changes in getID3 or the related Trac ticket (#49945).

Moment.js

The Moment.js library has been updated from version 2.22.2 to 2.27.0. For more information, check out the full list of changes in Moment.js, or the related Trac ticket (#50408).

clipboard.js

The clipboard.js library has been updated from version v2.0.4 to v2.0.6. For more information, check out the related Trac ticket (#50306).

Props @earnjam for technical review, @newyorkerlaura and @justinahinon for proof reading.

#5-5, #dev-notes, #external-libraries

WordPress 5.5: Better fine grained control of redirect_guess_404_permalink()

Since WordPress 2.3.0, the redirect_guess_404_permalink() function has existed to attempt guessing the desired URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org based on the query variables available. This is especially useful when a post’s parent changes (for hierarchical post types), or a post’s slug is changed.

Guessing a URL to redirect 404 requests is fine for the majority of WordPress sites, but sitesite (versus network, blog) owners, developers, 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 authors may want more fine grained control over the guessing logic.

This is a long-standing issue, as the original ticketticket Created for both bug reports and feature development on the bug tracker. was opened 9 years ago. So long, WordPress 5.5 will add the ability to manage that feature properly.

Short-circuiting default guessing logic

The new pre_redirect_guess_404_permalink 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. can now be used to short-circuit the function, bypassing the default guessing logic. This is useful to execute custom logic that better fits each individual site’s needs to makemake A collection of P2 blogs at make.wordpress.org, which are the home to a number of contributor groups, including core development (make/core, formerly "wpdevel"), the UI working group (make/ui), translators (make/polyglots), the theme reviewers (make/themes), resources for plugin authors (make/plugins), and the accessibility working group (make/accessibility). a more accurate guesses.

Returning a non-false value to the filter will cause the function to return the filtered value early.

Example

function mysite_pre_redirect_guess_404_permalink() {
    // Custom redirect URL guessing logic.
   return $new_redirect_url;
}
add_filter( 'pre_redirect_guess_404_permalink', 'mysite_pre_redirect_guess_404_permalink' );

Controlling “strict” vs. “loose” comparison

The strict_redirect_guess_404_permalink can now be used to filter whether a “strict” or “loose” comparison is used to make a redirect URL guess.

“Strict” comparisons (true) will make a guess suggestion for a redirect only when exact post_name matches are found.

“Loose” comparisons (false) is the default option and will perform a LIKE query on post_name.

Example

The following example will enable “strict” comparisons in redirect_guess_404_permalink():

add_filter( 'strict_redirect_guess_404_permalink', '__return_true' );

Disable 404 redirect guessing

The do_redirect_guess_404_permalink filter can now be used to completely disable redirect guessing. Returning false to the filter will disable the feature entirely.

Example

add_filter( 'do_redirect_guess_404_permalink', '__return_false' );

For more information on these changes, consult the related TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticket: #16557.

#5-5, #dev-notes, #permalinks

WordPress 5.4.2: Prevent unmoderated comments from search engine indexation

WordPress 5.1 previously added the possibility to show the “awaiting moderation” message on comments list when comment cookies are disabled. Indeed, this changeset included a hash in the redirect URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org, allowing the website to identify that a preview of the moderated comment should be displayed. By providing an hash in the URL when users did not consent to cookies, the changeset also provided a way to spammers to share an URL that actually contain their messages, and this URL was potentially indexable by search engines.

In WordPress 5.4.2, after a comment is submitted, only a brief window will be available to publicly see the awaiting moderation comment on the website. This change prevents search engines from indexing URLs that may contain spammy messages.

Here is the full list of changes:

  • Remove unapproved comments preview after 1 minute to avoid public access through the moderation hash.
  • Only pass querystring parameters if the user did not consent to cookies, otherwise they are not required.
  • For requests with the unapproved and moderation hash querystring parameters, Expires and Cache-Control 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. headers of 60 seconds are added for CDN and other cache hinting services.
  • Only display the requested comment if the querystring parameters are included in the request.
  • Hide the reply button on unapproved comment if it is displayed due to the moderation hash.

This is not considered as a security issuesecurity issue A security issue is a type of bug that can affect the security of WordPress installations. Specifically, it is a report of a bug that you have found in the WordPress core code, and that you have determined can be used to gain some level of access to a site running WordPress that you should not have.. Those changes were discussed publicly on Trac and milestoned to WordPress 5.4.2 point releaseMinor Release A set of releases or versions having the same minor version number may be collectively referred to as .x , for example version 5.2.x to refer to versions 5.2, 5.2.1, 5.2.3, and all other versions in the 5.2 (five dot two) branch of that software. Minor Releases often make improvements to existing features and functionality. few weeks ahead of the releaseRelease A release is the distribution of the final version of an application. A software release may be either public or private and generally constitutes the initial or new generation of a new or upgraded application. A release is preceded by the distribution of alpha and then beta versions of the software. date.

However, given the inconvenience caused by this issue, the WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. team decided to exceptionally backportbackport A port is when code from one branch (or trunk) is merged into another branch or trunk. Some changes in WordPress point releases are the result of backporting code from trunk to the release branch. those changes to each affected branchbranch A directory in Subversion. WordPress uses branches to store the latest development code for each major release (3.9, 4.0, etc.). Branches are then updated with code for any minor releases of that branch. Sometimes, a major version of WordPress and its minor versions are collectively referred to as a "branch", such as "the 4.0 branch". of WordPress, from WP 5.1 to WP 5.4.

For reference, see the related TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker.: #49956

#5-4-2, #dev-notes

Fullscreen mode enabled by default in the editor

Starting with WordPress 5.4, the editor behaves differently the first time you open the editor in a new installation or on a new device—or any other time WordPress resets the user preferences.

Now the editor opens in fullscreen mode by default. Note that for now, that’s a local setting, which is why it’s going to reset when your preferences do, including incognito mode. Future releases will store the setting in the WordPress database.

Want to turn it off? It’s simple—just use the pulldown in the editor’s menu.

You can also control the editor’s mode programmatically with the data module. A quick reminder: the code below is 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/., not PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20.

const isFullscreenMode = wp.data.select( 'core/edit-post' ).isFeatureActive( 'fullscreenMode' );

if ( isFullscreenMode ) {
    wp.data.dispatch( 'core/edit-post' ).toggleFeature( 'fullscreenMode' );
}

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

New gradient theme APIs

WordPress 5.4 lets your theme use gradients as backgrounds in Cover and Buttons blocks, courtesy of some new theme APIs. You’ll notice they parallel the approaches of the colors and fonts 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..

Configure the predefined set of gradients

Start by configuring a predefined set of gradients. Do that with the theme-support option editor-gradient-presets, then pass an array that represents the gradient set:

add_theme_support(
    'editor-gradient-presets',
    array(
        array(
            'name'     => __( 'Vivid cyan blue to vivid purple', 'themeLangDomain' ),
            'gradient' => 'linear-gradient(135deg,rgba(6,147,227,1) 0%,rgb(155,81,224) 100%)',
            'slug'     => 'vivid-cyan-blue-to-vivid-purple'
        ),
        array(
            'name'     => __( 'Vivid green cyan to vivid cyan blue', 'themeLangDomain' ),
            'gradient' => 'linear-gradient(135deg,rgba(0,208,132,1) 0%,rgba(6,147,227,1) 100%)',
            'slug'     =>  'vivid-green-cyan-to-vivid-cyan-blue',
        ),
        array(
            'name'     => __( 'Light green cyan to vivid green cyan', 'themeLangDomain' ),
            'gradient' => 'linear-gradient(135deg,rgb(122,220,180) 0%,rgb(0,208,130) 100%)',
            'slug'     => 'light-green-cyan-to-vivid-green-cyan',
        ),
        array(
            'name'     => __( 'Luminous vivid amber to luminous vivid orange', 'themeLangDomain' ),
            'gradient' => 'linear-gradient(135deg,rgba(252,185,0,1) 0%,rgba(255,105,0,1) 100%)',
            'slug'     => 'luminous-vivid-amber-to-luminous-vivid-orange',
        ),
        array(
            'name'     => __( 'Luminous vivid orange to vivid red', 'themeLangDomain' ),
            'gradient' => 'linear-gradient(135deg,rgba(255,105,0,1) 0%,rgb(207,46,46) 100%)',
            'slug'     => 'luminous-vivid-orange-to-vivid-red',
        ),
    )
);

For more, see https://developer.wordpress.org/block-editor/developers/themes/theme-support/#block-gradient-presets.

Disable custom gradients

You can also disable custom gradients:

add_theme_support( 'disable-custom-gradients' );

This call limits your users to the default gradients you defined in 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 or that you added to the editor-gradient-presets theme support setting.

For more, see https://developer.wordpress.org/block-editor/developers/themes/theme-support/#disabling-custom-gradients.

Disable gradient functionality

You can also use these APIs to shut down gradient functionality altogether. Just combine these two calls:

add_theme_support( 'disable-custom-gradients' );
add_theme_support( 'editor-gradient-presets', array() );

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

Markup and style-related changes

WordPress 5.4 makes several DOM structure changes on 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. Ideally, your code doesn’t depend on WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. class names or a specific DOM, since class names and the DOM structure are not part of the WordPress public API.

Remove legacy “editor-” class name compatibility

WordPress 5.2 updated the CSSCSS Cascading Style Sheets. class names of a lot of the components in the block editor, changing editor- prefixes on those class names to block-editor-. Where the old class names still existed, largely in component references, the conventional wisdom urged developers to avoid those references or update them accordingly.

In WordPress 5.4, these old editor--prefixed class names are gone from components in the block-editor scripts. If you’re still referencing the editor-prefixed CSS class name of a component, you’ll need to update to the block-editor- equivalent.

Div with class edit-post-layout__content removed

The `edit-post-layout__content` div is gone from the DOM of the block editor. Check your custom styles 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 files to makemake A collection of P2 blogs at make.wordpress.org, which are the home to a number of contributor groups, including core development (make/core, formerly "wpdevel"), the UI working group (make/ui), translators (make/polyglots), the theme reviewers (make/themes), resources for plugin authors (make/plugins), and the accessibility working group (make/accessibility). sure you’re not targeting it fir styling.

Blocks and rich text components lose redundant wrappers

Blocks and RichText have been refactored to simplify and lighten the ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. and DOM tree.

The key to this refactor: moving controls out of the elements and into adjacent popovers, which made four div wrappers redundant—so now they’re gone.

The result: significant performance improvement—and the editor-content DOM looks a lot more like the front end. So styling blocks is now a lot easier for both block and theme authors. Eventually, the plan is to let blocks render the very same tree in the editor as on the front end.

Here’s how those changes have affected the block-editor DOM:

The block-editor-rich-text class is now part of the editable element, unless you’re still using the wrapperClasses prop (which you should really stop using). If you really need a wrapper around the editable element, you’re better off creating your own.

The data-block attribute, containing the block ID, has relocated to the outer block wrapper element. The block-editor-block-list__block-edit class is gone completely; so is the div element. Selectors like .wp-block > .block-editor-block-list__block-edit > [data-block] won’t work anymore. Use .wp-block or just the [data-type] attribute instead.

Simpler block margins

 17877 changes the way the block editor lays out blocks. Before now, every block came with built-in padding, left and right, and negative margins to compensate.

Well, in a bid to radically simplify the CSS you need to style blocks, to develop blocks, to build themes and style the editor in your themes, the built-in padding and negative margins are refactored out of existence—they’re GONE.

Now, if your current block or editor styles have been compensating for those previous margins/paddings, they might look a little off in version 5.4. If so, try getting rid of the styles you wrote to compensate.

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

General Block Editor API Updates

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. attribute sources deprecated in 5.4

WordPress 5.4 deprecates meta attribute sources.

Your existing code that uses these attributes should still work, but there’s a new way to get where you want to go.

Instead of meta attributes, use EntityProvider and related 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. APIs. EntityProvider and related hooks APIs provide a more flexible and powerful way to build blocks that source data from a variety of properties of WordPress entities and data.

Here’s how 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.’s objects can permit reading and writing to the meta of a post:

const [meta, setMeta] = useEntityProp('postType', 'post', 'meta')

ShortcodeShortcode A shortcode is a placeholder used within a WordPress post, page, or widget to insert a form or function generated by a plugin in a specific location on your site. transforms: Support isMatch predicate

To bring shortcodes in line with other types of block transformations, you can add an optional isMatch function to see if a given shortcode should transform into a specific block.

For instance, this hypothetical Antarctica Weather block only cares about [weather] shortcodes for Antarctica:

transforms: {
    from: [
        {
            type: 'shortcode',
            tag: 'weather',
            isMatch( { named: { latitude } } ) {
                return parseInt( latitude, 10 ) < -70;
            },
            attributes: {
                latitude: {
                    type: 'number',
                    shortcode: ( { named: { latitude } } ) =>
                        parseInt( latitude, 10 ),
                },
                longitude: {
                    type: 'number',
                    shortcode: ( { named: { longitude } } ) =>
                        parseInt( longitude, 10 ),
                },
            },
        },
    ],
},

If isMatch returns false, the shortcode won’t become an Antarctica Weather block. At that point, another block type can pick it up (presumably, one that matches the [weather] shortcode), or it can stay a shortcode and get encapsulated in a Shortcode block.

New AsyncModeProvider 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.

Because nobody wants laggy typing in the Editor, the BlockEditor uses an Async Rendering Mode: The selected block gets rerendered synchronously on each change—while the unselected blocks only refresh when the browser goes idle (i.e., while it’s not actively doing some task).

That behavior comes courtesy of the Async Mode, implemented in the wordpress/data package.

In WordPress 5.4, you can use that same sort of asynchronous behavior to speed things up in your own ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. state trees—as long as they rely on the data module.

That’s because version 5.4 puts the AsyncModeProvider component where you can find it and use it — or, conversely, not use it, since you can also use it to opt out of the block async rendering mode.

import { AsyncModeProvider } from '@wordpress/data';
const MyComponent = () => {
  return (
    <>
        The following component updates synchronously on data store changes
        <MySyncComponent />
        <AsyncModeProvider value={ true }>
            The following component updates asynchronously on data store changes
            <MyAsyncComponent />
        </AsyncModeProvider>
    </>
  );
}

For more about the AsyncMode, you can check this blog post.

A custom media upload handler in a block editor. In a SETTING!

Did you know? You can use the wordpress/block-editor package by itself, to add block-editor pages just about anywhere. Use it for custom WPAdmin pages or even in a completely WordPress-agnostic context.

Here’s an example from the Gutenberg Playground. In a situation like this, WordPress 5.4 lets you add a custom media-upload handler to the block editor—as a setting! (One of your users probably wants this right now.)

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

/**
 * Media Upload Handler
 *
 * @param   {Object}   $0                   Parameters object passed to the function.
 * @param   {?Object}  $0.additionalData    Additional data to include in the request.
 * @param   {string}   $0.allowedTypes      Array with the types of media that can be uploaded, if unset all types are allowed.
 * @param   {Array}    $0.filesList         List of files.
 * @param   {?number}  $0.maxUploadFileSize Maximum upload size in bytes allowed for the site.
 * @param   {Function} $0.onError           Function called when an error happens.
 * @param   {Function} $0.onFileChange      Function called each time a file or a temporary representation of the file is available.
 */
const myMediaUploadHandler = ( settings ) => {
   const mediaObject = {
      id, alt, caption, title, url,
   };    

    settings.onFileChange([mediaObject]);
}

const MyCustomEditor = () => {
  return (
        <BlockEditorProvider settings={ { mediaUpload: myMediaUploadHandler  } }>
            <MyEditorLayout />
        </BlockEditorProvider>
  );
}

Now, realize this: if you leave the mediaUpload handler out of your BlockEditor instance, your editor won’t support media upload at all. Or, it might not let the current user upload media with their current permissions.

You can also give Media Blocks access to this setting in their edit functions, so they can support uploads.

const MyBlockEdit = () => {
   const mediaUpload = useSelect( ( select ) => {
      return select( 'core/block-editor' ).getSettings().mediaUpload;
   }, [] );

   return (
      <>
           { !! mediaUpload && <MyMediaUploadComponent onUpload={ mediaUpload } /> }
       </>
   );
   <
}

Easier drag-and-drop

Do you get complaints about drag-and-drop being more like swing-and-miss? In WordPress 5.4, you can listen to sweet, sweet silence.

That’s because the positioning classes that rendered in the DropZone component (is-close-to-topis-close-to-bottomis-close-to-left and is-close-to-right) are GONE.

In fact, the drop zone is gone. So users have a much bigger target to grab in the blocks they want to move. Easier grab, easier drag, happier users. And you’re the hero.

And with the exit of the drop zone, the editor.BlockDropZone component 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. is also gone. That filter was originally supposed to filter media uploads that happened by drag-and-drop— but it didn’t seem to be doing the job well.

If you’d been using that filter, and its removal is a problem, please leave a comment on this note. If there’s enough demand, it’s possible a filter like it, focused on a broader media-upload use case, could emerge from the discussion.

RichText: don’t set focus when applying format

When you’re formatting text in a rich-text instance, does it annoy you to see the focus go back automatically to the editable element? Do your users complain about that behavior?

Well, get happy! In support of more complex UIUI User interface, to give your users better control of rich-text instances, (e.g. a color control: who wants to have to click back into the color UI for every color change?) the focus will stay where you (or your users) are working until all the color changes, or whatever, are DONE.

Of course, that means that if you do want to keep setting the focus back, say, after a button click, you’ll have to actively makemake A collection of P2 blogs at make.wordpress.org, which are the home to a number of contributor groups, including core development (make/core, formerly "wpdevel"), the UI working group (make/ui), translators (make/polyglots), the theme reviewers (make/themes), resources for plugin authors (make/plugins), and the accessibility working group (make/accessibility). that happen when you’re registering the format type.

You’ll want to do that with the new onFocus function for the edit component.

For example, here’s how that works with the bold format button: https://github.com/WordPress/gutenberg/blob/c5eb9626dc1c73ad9bc543a5d171e9ab4a840996/packages/format-library/src/bold/index.js#L21-L53

New Guide component

A new Guide component was added to the @wordpress/components package (wp.components.Guide). Guide allows developers to easily create a step-by-step guide to display to users. The block editor uses Guide to implement a new welcome modal which appears on first launch.

Guide is a React component that renders a user guide in a modal. The guide consists of several GuidePage components which the user can step through one by one. The guide is finished when the modal is closed or when the user clicks Finish on the last page of the guide.

function MyTutorial() {
    const [ isOpen, setIsOpen ] = useState( true );

    if ( ! isOpen ) {
        return null;
    }

    <Guide onFinish={ () => setIsOpen( false ) }>
        <GuidePage>
            <p>Welcome to the ACME Store! Select a category to begin browsing our wares.</p>
        </GuidePage>
        <GuidePage>
            <p>When you find something you love, click <i>Add to Cart</i> to add the product to your shopping cart.</p>
        </GuidePage>
    </Guide>
}

Deprecation of wordpress/nux

The @wordpress/nux package (wp.nux) has been deprecated along with the DotTip component that it contained. Importing the package will display a warning in the browser console. It is recommended that plugins using wp.nux and DotTip migrate to Guide instead.

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

Privacy Updates in 5.4

WordPress 5.4 brings several improvements to the privacy tools to improve the user experience and expand upon the data provided in personal data exports.

Personal Data Export now includes Session Tokens, Community Events Location and Custom User MetaMeta Meta is a term that refers to the inside workings of a group. For us, this is the team that works on internal WordPress sites like WordCamp Central and Make WordPress..

In WordPress 5.4 the Personal Data exports were expanded upon to ensure the Personally Identifiable Information (PII) present in Session Tokens (#45889) and the Community Events Location (#43921) user data were made available to the exporting user. This data is made available in the export as custom group sections.

Session Tokens grouping
Community Events Location grouping

Along with the new groupings which will automatically be included in the export if the relevant data is available, developers can now expand upon the User profile data grouping through the use of the new wp_privacy_additional_user_data 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..

// Privacy Filter for adding additional user meta to personal data exports.
function my_custom_additional_user_profile_data( $additional_profile_data, $user, $reserved_names ) {
	return array(
		array(
			'name'  => __( 'Data one', 'a-plugin' ),
			'value' => 'one',
		),
		array(
			'name'  => __( 'Data two', 'a-plugin' ),
			'value' => 'two',
		),
		array(
			'name'  => __( 'Data three', 'a-plugin' ),
			'value' => 'three',
		),
		array(
			'name'  => __( 'Data four', 'a-plugin' ),
			'value' => 'four',
		),
	);
}
add_filter( 'wp_privacy_additional_user_profile_data', 'my_custom_additional_user_profile_data', 10, 3 );

Note: The $reserved_names array is supplied to the filter to assist developers in avoiding using these names in their array of additional data. This is due to any additional data matching these names will be suppressed from the export to avoid a conflictconflict A conflict occurs when a patch changes code that was modified after the patch was created. These patches are considered stale, and will require a refresh of the changes before it can be applied, or the conflicts will need to be resolved. with the existing user profile data to be exported.

See #47509

Personal Data Exports now include a 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. file and a Table of Contents

Along with including additional data in the Personal Data Exports the export zip will now contain a JSON file (#49029) of the data for better portability. This JSON file will contain all of the data present in the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. file with the exception of the table of contents.

The HTML export file has been updated to include a Table of Contents (#46894) for easier navigation of large data exports.

Visual Improvements to the Privacy Tools tables

In WordPress 5.4 the Privacy Tools tables have been updated to give progress indicators (#44264) for both the export and erasure processes. As well as switched the ‘Next Steps’ buttons to links (#49323) for a cleaner interface.

New filters for the headers of all Privacy-related emails

In WordPress 5.4 developers are now able to filter the email headers on privacy related emails. For example, this will enable developers to change the “From” email address. These headers and an example are listed below;

  • wp_privacy_personal_data_email_headers
  • user_request_action_email_headers
  • user_request_confirmed_email_headers
  • user_erasure_complete_email_headers
// Privacy filter for setting the From name/email on privacy emails.
function my_privacy_mail_headers( $headers, $subject, $content, $request_id, $email_data ) {
	$headers = array(
		'From: My Name <myname@example.com>',
	);
	return $headers;
}
add_filter( 'wp_privacy_personal_data_email_headers', 'my_privacy_mail_headers', 10, 5 );
add_filter( 'user_request_action_email_headers', 'my_privacy_mail_headers', 10, 5 );
add_filter( 'user_request_confirmed_email_headers', 'my_privacy_mail_headers', 10, 5 );
add_filter( 'user_erasure_complete_email_headers', 'my_privacy_mail_headers', 10, 5 );

See #44501

Renamed Function for Clarity

In WordPress 5.4 the wp_get_user_request_data function was renamed to wp_get_user_request for function clarity. This is due to the function returning the actual WP_User_Request object and not the data parameter which is part of the request object. The old function signature will now produce a _doing_it_wrong warning message.

See #46302

#5-4, #core-privacy, #dev-notes, #privacy

REST API Changes in 5.4

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. “OR” Relation Now Supported in Posts Controller

Querying for /wp/v2/posts?tags=1&categories=2 returns all posts assigned the 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 ID 1, AND assigned the categoryCategory The 'category' taxonomy lets you group posts / content together that share a common bond. Categories are pre-defined and broad ranging. with ID 2. This AND relationship, where multiple taxonomies’ term relationships must all be satisfied, has been the only supported behavior in these collection endpoints since WordPress 4.7.

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/. /wp/v2/posts endpoint, as well as 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. endpoints extending from WP_REST_Posts_Controller (including custom post types specifying "show_in_rest" => true), now supports a new tax_relation parameter which can be used to return posts matching either taxonomy 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., rather than both.

As an example, in WordPress 5.4, the posts endpoint query

/wp/v2/posts?tags=1&categories=2&tax_relation=OR

will now return posts in either the tag ID 1 or the category with ID 2.

Selective Link Embedding

The REST API now supports returning a limited set of embedded objects using the _embed parameter. As an example, in WordPress 5.4, the following query only embeds the author information instead of including all the comments, media, etc…

/wp/v2/posts/?_embed=author

All embeds will be returned if a value for the _embed parameter is omitted, or set to true or 1.

WP_REST_Server method changes

WordPress 5.4 changes the signature of two methods in the WP_REST_Server class. Developers who are extending WP_REST_Server and overriding these methods should update their code to match the new signatures to avoid PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 warnings.

  1. The signature of WP_REST_Server::embed_links() is now embed_links( $data, $embed = true ). The new $embed paramter accepts an array of link relations (such as array( 'author', 'wp:term' )) and limits the embedded links in the response to those relations. The default of true maintains the previous behavior of embedding all links in the response. For more details, see #39696.
  2. The signature of WP_REST_Server::get_routes() is now get_routes( $namespace = '' ). The new $namespace parameter accepts a string and limits the returned routes to those whose namespace matches the string. Internally, WP_REST_Server uses this new parameter to improve the performance of WP_REST_Server::dispatch() by reducing the number of regex checks necessary to match a request to a registered route. For more details, see #48530.

For performance reasons, WP_REST_Server::embed_links() also now caches response data in memory. This cache is managed by WP_REST_Server::response_to_data(). Code calling the protected embed_links method being called directly may need to be updated to ensure stale data is not returned.

(Thank you to @dlh for authoring this section)

See the full list of REST API changes on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

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

New @wordpress/create-block package for block scaffolding

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. scaffolding is a shorthand term that describes the supporting directory structure you need for WordPress to recognize a block. Typically that directory includes files like index.php, index.js, style.css and perhaps others—which in turn hold calls like register_block_type.

You’ve likely noticed a lot of tools that aim to automate the scaffolding build—or at least makemake A collection of P2 blogs at make.wordpress.org, which are the home to a number of contributor groups, including core development (make/core, formerly "wpdevel"), the UI working group (make/ui), translators (make/polyglots), the theme reviewers (make/themes), resources for plugin authors (make/plugins), and the accessibility working group (make/accessibility). it easier to build your own blocks. They’re nothing new in the WordPress ecosystem. And there’s even one in WP-CLIWP-CLI WP-CLI is the Command Line Interface for WordPress, used to do administrative and development tasks in a programmatic way. The project page is http://wp-cli.org/ https://make.wordpress.org/cli/: the wp scaffold block command.

You’ve probably also noticed that some of those third-party tools get you up and running with just one npx command, while WP-CLI still needs a full WordPress installation to run. And WP-CLI doesn’t play well with advanced 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/. tooling like code transpiling, linting or formatting.

Until now.

WordPress 5.4 brings you a brand-new, officially supported npm-based scaffolding package.

Create Block generates PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20, JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. and CSSCSS Cascading Style Sheets. code—and everything else you need to start building your 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. Its quick-start mode lets you pass it a slug that then becomes both the target location for the generated files AND the internal block name:

$ npm init @wordpress/block todo-list
wordpress-create-block

You don’t need to install or configure tools like webpack, Babel or ESLint yourself. They’re preconfigured and out of sight. So you can focus on the code.

Create Block also has an interactive mode that lets you customize several essential block options before code generation:

$ npm init @wordpress/block

Finally, despite its support for modern JavaScript tooling, Create Block also lets you to pick an ES5 template—and skip the transpiling tools that trigger ESNext and JSX support.

Note: If you’re concerned about backwards compatibility, the new tool comes straight from the existing WP-CLI implementation—and in particular, the optional ES5 template uses the existing ES5 code.

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