Miscellaneous Editor Changes in WordPress 7.2

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

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

Removed __experimentalGroup prop from InspectorControls

WordPress 7.2 removes the __experimentalGroup prop from InspectorControls and InspectorControls.Slot. Use the group prop instead. (#83171)

The prop was stabilized as group in WordPress 6.2 (#47105). Since then, passing __experimentalGroup logged a deprecation warning that named WordPress 6.4 as the removal version. WordPress 7.2 completes that removal.

Code that still passes __experimentalGroup now renders its controls in the default group, with the block’s other settings. For example, controls meant for the Advanced panel now appear outside it. A ToolsPanelItem meant for a panel such as Typography renders without that panel around it.

To update, rename the prop. The group prop works in WordPress 6.2 and later, so no version check is needed:

// Before
<InspectorControls __experimentalGroup="advanced">
	<TextControl label={ __( 'Custom ID' ) } value={ id } onChange={ setId } />
</InspectorControls>

// After
<InspectorControls group="advanced">
	<TextControl label={ __( 'Custom ID' ) } value={ id } onChange={ setId } />
</InspectorControls>

For the Advanced panel, InspectorAdvancedControls is also available and sets group="advanced" for you.

References:

Deprecated __experimentalImageEditor component: stylesheet moved

The @wordpress/block-editor npm package and the wp.blockEditor global export an __experimentalImageEditor component for building image cropping and editing interfaces. The component was deprecated in WordPress 7.1, so avoid using it.

If your code still uses it, note a CSSCSS Cascading Style Sheets. change in WordPress 7.2. The component’s stylesheet was incorrectly defined in the @wordpress/block-library package. In 7.2 it moves to @wordpress/block-editor. Update any imports of the stylesheet to the new location.

References:

Additional CSS now applies to blocks rendered by a parent block

Starting in WordPress 7.2, Additional CSS (set in a block’s Advanced panel) works for blocks that a parent block renders itself, such as a Navigation Link inside a Navigation block.

Before, that CSS was missing on the front end. CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. generated it only for blocks in a parent’s regular inner content. The Navigation block loads its inner blocks from a navigation menuNavigation Menu A theme feature introduced with Version 3.0. WordPress includes an easy to use mechanism for giving various control options to get users to click from one place to another on a site. post, so those blocks skipped that step.

Now the CSS is generated when each block renders, however its parent loaded it. Blocks that already worked are unaffected, and their CSS is not duplicated.

No code changes are needed. Rules that were previously ignored will now apply, so check for any you don’t want.

References:

Core Data

registry.subscribe no longer listens to all stores when the store is not registered yet

Starting in WordPress 7.2, registry.subscribe( listener, storeName ) is more efficient when storeName isn’t registered at the time of the call.

Previously, the listener was attached to the registry-wide listener list, so it ran on every update from every store, both before and after the target store was registered. Now the registry keeps it as a pending listener and connects it to the store once it is registered, so the listener only runs for updates from that store.

Subscribing before a store is registered works as before, and the returned unsubscribe function still works. No code changes are needed. Code that relied on such a listener firing for unrelated stores will see fewer calls, but this was never documented behavior.

References:


Props to @aaronrobertshaw, @ramonopoly, @annezazu, @jsnajdr, @scruffian for content.

#7-2, #dev-notes, #dev-notes-7-2

API for style state-aware block styling controls

Custom 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. controls can now make use of the responsive and pseudo state styling system in the block editor. To implement this, controls for editing styles need to read and update the block’s style attribute for the state selected in the editor. 7.2 exposes a public 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. for this.

The following 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. and selectors from @wordpress/block-editor work with both viewport and pseudo states:

getSelectedBlockStyleState reads the selected state;
hasSelectedBlockStyleState checks whether a non-default state is selected;

getStyleForState Returns the style object for the selected state;
setStyleForState Sets the new style on the selected state.

import {
    getStyleForState,
    setStyleForState,
    store as blockEditorStore,
} from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';

const selectedState = useSelect(
    ( select ) =>
        select( blockEditorStore ).getSelectedBlockStyleState( clientId ),
    [ clientId ]
);

const stateStyle = getStyleForState( attributes.style, selectedState ) || {};

setAttributes( {
    style: setStyleForState( attributes.style, selectedState, {
        ...stateStyle,
        dimensions: {
            ...stateStyle.dimensions,
            minHeight: '50vh',
        },
    } ),
} );

Displaying controls in the toolbar and inspector

By default inspector controls are hidden when a style state is selected. To display custom controls in the inspector when a viewport or a pseudo state is enabled, the style-state slot is available:

<InspectorControls group="style-state">
    <MyStyleStateControl />
</InspectorControls>

To display custom controls in the block toolbar when a viewport state is enabled, there is also a style-state slot:

<BlockControls group="style-state">
    <MyViewportControl />
</BlockControls>

(The default block toolbar slots aren’t currently hidden for pseudo states.)

Obtaining media query strings

For viewport state integrations that need media query strings, @wordpress/global-styles-engine also exports getViewportMediaQueries:

import { getViewportMediaQueries } from '@wordpress/global-styles-engine';

const mediaQueries = getViewportMediaQueries( {
    mobile: '480px',
    tablet: '782px',
} );

// {
//   '@mobile': '@media (width <= 480px)',
//   '@tablet': '@media (480px < width <= 782px)',
// }

Calling getViewportMediaQueries with no parameters will return the default coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. media queries (with 480px for mobile and 782px for tablet).

PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher code can use the corresponding wp_get_viewport_media_queries helper:

<?php
$media_queries = wp_get_viewport_media_queries(
    array(
        'mobile' => '480px',
        'tablet' => '782px',
    ),
    array(
        'include_desktop' => true,
    )
);

// Includes @mobile and @tablet, plus:
// '@desktop' => '@media (width > 782px)'

Calling wp_get_viewport_media_queries with no parameters will return the default core media queries (with 480px for mobile and 782px for tablet).
include_desktop defaults to false.

See the block editor data reference and GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ PR #82741.


Props to @andrewserong, @aaronrobertshaw and @talldanwp for review.

#7-2, #dev-notes, #dev-notes-7-2

Preparing for jQuery 4 with WordPress 7.2

The last major jQuery update in WordPress was to version 3 back in 2020, and was a process carried out over multiple releases, with the final step culminating in the disabling of jQuery Migrate by default (this final step was never finalized at the time).

WordPress 7.2 will ship with jQuery Migrate 3.6.0 to prepare for updating to jQuery 4 in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. Doing so will help extenders catch deprecation notices in their code for features that may no longer be available in jQuery 4.

The planned process is currently:

  • Update jQuery Migrate in WordPress 7.2
  • Update to the latest release of jQuery and jQuery Migrate tentatively planned for WordPress 7.3 depending on test results. Updating to the latest jQuery UIUI User interface and other libraries dependent on jQuery is also planned for 7.3.
  • Disable jQuery Migrate by default at the end of 2027 (WordPress 7.5 or 7.6, depending on the release cadence for next year), this is also dependent on testing and research into the potential impact on the ecosystem.

You can follow the progress of updating to jQuery 4 in #60478


Props to @davidbaumwald and @pbiron for copy review.

#7-2, #dev-notes, #dev-notes-7-2, #jquery

Media changes in WordPress 7.2

WordPress 7.2 extends client-side media processing beyond 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, stops rewriting crossorigin attributes on the editor page, and generates animated sub-sizes for animated GIF and WebP uploads.

In short:

  • Image uploads from the Media Library grid, the Add New Media File screen and the media modal now go through the client-side pipeline in supported browsers.
  • wp_start_cross_origin_isolation_output_buffer() and wp_add_crossorigin_attributes() are deprecated. wp_send_document_isolation_policy_header() replaces the first; the second has no replacement.
  • Sub-sizes of animated GIF and WebP images keep their animation on the client-side path. The new wp_generate_animated_image_subsizes 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. turns that off.

Client-side media processing now covers the Media Library and media modal

WordPress 7.1 introduced client-side media processing: in a cross-origin isolated page, the block editor uploads the original image through 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/, generates the sub-sizes in the browser with wasm-vips, then sideloads them and finalizes the attachment. This takes image processing off the server and gives the same results regardless of which image libraries the server has.

In 7.1 this only ran in the block editor. The Media Library grid, the Add New Media File screen and the media modal still uploaded through wp.Uploader and plupload to async-upload.php, with all processing on the server. A HEIC file that converted when dropped on an Image block could fail in the media modal on a server without HEIC support (#65661, #66220).

What changed in 7.2

Uploads from these three places now use the same pipeline as the editor:

  • The Media Library grid (upload.php in grid mode).
  • The Add New Media File screen (media-new.php).
  • The media modal, meaning every wp.media frame that uploads through wp.Uploader: the Image block’s “Media Library” button, the featured imageFeatured image A featured image is the main image used on your blog archive page and is pulled when the post or page is shared on social media. The image can be used to display in widget areas on your site or in a summary list of posts. panel, and the same frame in the site editor and the block widgets screen.

The existing UIUI User interface is reused, so progress bars, grid tiles and error notices look and behave as before. Error messages come from the pipeline, so the platform-specific HEIC wording from the editor shows up on these screens too. While an upload is in flight, the page warns before navigating away, since an interrupted client-side upload could lose sub-sizes that were not yet sideloaded.

Cross-origin isolation on more screens

wp_set_up_cross_origin_isolation() now also runs on load-upload.php and load-media-new.php. The Media Library is only isolated in grid mode, since list mode uploads go through the Add New Media File screen. The action query parameter check that skips third-party editors does not apply to these screens.

New functions:

  • wp_is_document_isolation_policy_supported() returns whether the requesting browser honors the headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes., based on its User-Agent. Today that means Chromium 137 or newer.
  • wp_is_cross_origin_isolated_request() returns whether coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. isolated the current response, meaning wp_send_document_isolation_policy_header() (see below) sent the header. A header 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. sends itself does not count.
  • wp_get_media_library_mode() returns grid or list using the same resolution as upload.php, without updating the saved user option.
  • wp_get_media_library_upload_settings() returns the settings the pipeline needs: maximum upload size, allowed mime types, the registered image sub-sizes, and the image processing settings described below.
  • wp_enqueue_media_frame_upload() and wp_enqueue_media_new_upload() enqueue the screen scripts. wp_enqueue_media() calls the first one, so most code never needs to.

The image processing settings pass through the same filters the server uses: big_image_size_threshold, image_strip_meta and image_max_bit_depth. A plugin that changes them affects client-side uploads too. Because the server never decodes the image on this path, image_max_bit_depth receives 16, the maximum the client encoder can produce, as both its value and the current depth.

Three scripts were added: media-upload-pipeline, which configures the @wordpress/upload-media store and exposes wp.mediaUploadPipeline, plus media-frame-upload and media-new-upload, which hand files added to the existing uploader to the pipeline. They are only enqueued when client-side media processing is enabled, the browser supports Document-Isolation-Policy and core isolated the request.

What still uses the classic upload

When client-side processing is turned off with the wp_client_side_media_processing_enabled filter, or the browser does not support it (Firefox and Safari today), uploads work as they did in 7.1 through async-upload.php. Some uploads stay on the classic path even in a supported browser:

  • Anything that is not an image the pipeline can process (JPEG, PNG, GIF, WebP, AVIF, HEIC/HEIF). Audio, video, PDF, SVG, 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 archives upload through async-upload.php as before. So does an image whose type is not in the allowed mime types the page was rendered with, which leaves the decision to the server.
  • Uploaders that do not post attachments. Only uploaders using async-upload.php with the upload-attachment action are intercepted, so a plugin’s own wp.Uploader pointed elsewhere is left alone.
  • JPEG and PNG files while plupload resizing is enabled, through the “Scale images” setting or a resize value passed through plupload_init.
  • A HEIC file the browser cannot decode (Linux, and Windows without the HEVC extension), when the server’s image editor supports HEIC. When neither can convert it, the pipeline’s error is shown.
  • Screens core did not isolate: 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., the Site Icon picker, the classic editor’s media modal, and any screen where a plugin sends its own Document-Isolation-Policy header.

Extra multipart params added through plupload_default_params or wp.Uploader.param() are forwarded to the REST request, so they still arrive in $_POST.

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: sub-sizes count against the site’s upload space

On a multisite networknetwork (versus site, blog) with the “Site upload space” limit turned on, client-side media checks every file (including generated sub-sizes) against the site’s storage quota, not just the original.

On the classic path, only the original upload is checked (through check_upload_size() on wp_handle_upload_prefilter). The server then writes the sub-sizes straight to disk, so they never hit the quota check. With client-side media, each sub-size generated in the browser is a separate request to /wp/v2/media/{id}/sideload, and each one is checked for space left, the network’s maximum upload file size (fileupload_maxk) and the site quota.

In practice this only matters for a site that is close to its limit: the original fits, then some or all of the sub-sizes are rejected with rest_upload_limited_space or rest_upload_user_quota_exceeded.

When that happens:

  • If some sub-sizes fit, the image is saved with only those sizes. The missing sizes are not currently reported to the user.
  • If none fit, the upload fails: the attachment is deleted and the block resets. The error shown is the server’s message for the rejected sub-size, eg. “Not enough space to upload. 2 KB needed.”

Better handling for both cases is being worked on in #86834.

Note that networks with the upload space check disabled (the upload_space_check_disabled site option) are not affected.

A site that needs the old behavior can turn off client-side media processing:

add_filter( 'wp_client_side_media_processing_enabled', '__return_false' );

Sub-sizes in the attachment’s output format are allowed

Sideloaded sub-sizes also go through the network’s “Upload file types” setting (upload_filetypes). Networks created before 5.8 have no webp in that list and those created before 6.5 have no avif, so with a plugin filtering image_editor_output_format to either format, every sub-size was rejected and the upload failed.

In 7.2, the attachment’s output format is added to upload_filetypes for the duration of a sideload only, matching the classic path where the server writes sub-sizes in any output format. Other formats are still checked against the network setting, and a type removed through upload_mimes is still blocked. Single site is not affected.

Related: #66680, #66681, r65533.

Running the pipeline on a plugin’s own screen

The media frame integration only loads on a screen where wp_send_document_isolation_policy_header() sent the header. A Document-Isolation-Policy header a plugin sends itself does not count, so a page builder that isolates its editor for its own reasons keeps classic uploads in every wp.media frame on that screen, as in 7.1.

To opt a screen into the client-side pipeline, send the header through core before wp_enqueue_media() runs:

add_action( 'load-toplevel_page_my-plugin', function () {
	if ( wp_is_client_side_media_processing_enabled() ) {
		wp_send_document_isolation_policy_header();
	}
} );

The function returns false and sends nothing when headers were already sent or the browser does not support the header. Isolating a screen blocks same-origin access to iframes that are not isolated too, so test the screen before opting in.

The GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ plugin sends the header itself on the editor screens, so its media modal uses classic uploads until the site runs a Gutenberg release that includes #86542. Uploads made in the block editor itself are not affected.

Related: #66490, r65356, r65532.

What changes for upload 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.

Pipeline uploads go to the REST API (POST /wp/v2/media, then /sideload per sub-size and /finalize) instead of async-upload.php. Most upload hooks still run, but a few things differ:

  • Extra params added through plupload_default_params or wp.Uploader.param() are sent as POST fields, so they still arrive in $_POST and $_REQUEST. action, _wpnonce and post_id are not forwarded: the attachment’s parent is sent as post.
  • $_POST['action'] is not upload-attachment and DOING_AJAX is not defined. Code that detects media uploads that way will miss pipeline uploads; check for a REST request, or hook the upload filters directly.
  • The original file goes through wp_handle_upload(), so wp_handle_upload_prefilter and upload_mimes run as before. Sub-sizes generated in the browser go through wp_handle_sideload(), so they run wp_handle_sideload_prefilter.

Related: r64588, #12585, Gutenberg #82409.

The editor no longer rewrites crossorigin attributes

In 7.1 the editor page was buffered with ob_start() and rewritten with WP_HTML_Tag_Processor to add crossorigin="anonymous" to cross-origin scripts, stylesheets, audio and video, alongside the Document-Isolation-Policy: isolate-and-credentialless header. That caused two problems:

  • Running 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.) processor inside an output buffer display handler could end in a fatal error and a blank screen on Chromium 137+ when the page loaded any cross-origin resource (#65930).
  • Forcing crossorigin="anonymous" turns a subresource load into a CORS request, which fails for any host that does not send Access-Control-Allow-Origin, such as media offloaded to a CDN (#65673).

With isolate-and-credentialless, cross-origin subresources load without credentials instead of being blocked, so the attribute was never needed. In testing with current Chromium builds, resources without the attribute loaded identically with and without the header.

What changed in 7.2

  • The new wp_send_document_isolation_policy_header() sends the header and returns whether it did. It returns false if headers were already sent or the browser does not support Document-Isolation-Policy.
  • wp_set_up_cross_origin_isolation() now returns that boolean instead of void.
  • The editor page is no longer buffered or rewritten, and wp_print_media_templates() no longer adds crossorigin="anonymous" to AUDIO and VIDEO tags in the media modal templates.
  • wp_start_cross_origin_isolation_output_buffer() and wp_add_crossorigin_attributes(), both added in 7.1, are deprecated. They still exist and trigger a deprecation notice. The first now only sends the header; the second returns the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. unchanged, so calls can be removed.
// Before (7.1).
wp_start_cross_origin_isolation_output_buffer();

// After (7.2).
wp_send_document_isolation_policy_header();

What plugin and theme developers should check

  • Code that calls either deprecated function, or that parsed the editor output expecting crossorigin attributes, needs updating. Hooking or removing wp_set_up_cross_origin_isolation on the load-* actions keeps working.
  • Plugins that added their own crossorigin injection to make cross-origin media work in the editor can drop it. Under isolate-and-credentialless it is not required, and it breaks hosts without CORS headers.
  • To confirm isolation is active on a screen, check window.crossOriginIsolated in the browser console. In browsers without Document-Isolation-Policy support, such as Firefox and Safari, it is false and uploads use the server as before.
  • Safari support needs require-corp, which does need the attribute. The Client-Side Media Everywhere plugin keeps the injection for that case.
  • A response that has already sent headers before the load-* action fires cannot receive the policy header. Debug output or early echo calls in a plugin are the usual cause.

Related: r64489, #13446, Gutenberg #82614.

Animated image sub-sizes are generated by default

Resized versions of animated GIFs have always lost their animation, because both GD and Imagick flatten animated images when resizing #28474 (open since 2014). Server-side it stalled because GD cannot preserve frames at all, Imagick is only available on some hosts, and re-encoding every frame is costly on shared CPU.

Client-side media processing changes that. Decoding, scaling and encoding happen in the uploader’s browser, so every frame can be processed regardless of the host, and the cost is paid once by the uploader #65656.

What changed in 7.2

When client-side media processing is used, every sub-size of an animated GIF or WebP keeps its animation by default, including cropped sizes such as thumbnail, where each frame is cropped with the same rectangle. If an animation is too large to decode in the browser, the pipeline falls back to a static first-frame sub-size instead of failing the upload.

Server-side uploads still produce static sub-sizes. The change only affects the client-side path.

The wp_generate_animated_image_subsizes filter

The new filter takes a boolean and defaults to true. Returning false generates static first-frame sub-sizes, matching the server-side path, which keeps upload times down on low powered devices or sites that upload many large animations.

add_filter( 'wp_generate_animated_image_subsizes', '__return_false' );

The Disable Animated Sub-sizes plugin does exactly this, for sites that prefer not to add code.

The filtered value is exposed on the REST API index as generate_animated_image_subsizes, alongside image_size_threshold and image_max_bit_depth, for users who can upload_files. The Media Library screens receive the same value through wp_get_media_library_upload_settings().

What developers should check

  • Themes and plugins that assumed sub-sizes of an uploaded GIF or WebP are static first frames may now receive animated files, which are larger than a still frame.
  • wp_calculate_image_srcset() still declines to mix a full-size animated GIF with its sub-sizes in one srcset. With animated sub-sizes that guard is more conservative than it needs to be but harmless. Relaxing it is a possible follow-up.
  • The client-side code ships through the Gutenberg package sync (Gutenberg #80385), so the filter and the REST field are the core-side surface.

Related: r64490, #12572, #28474.

Unattached images are auto-attached to posts when saved in the block editor

In the classic editor, images are auto-attached to a post as soon as a user picks them from the Media Library. This feature has been a gap in the block editor, where only images uploaded to a post were auto-attached. In WordPress 7.2 when a post is saved in the block editor, unattached images are auto-attached. This occurs later in the process than in the classic editor, so that an image added and then removed is not auto-attached.

Some details:

  • This only runs on a successful manual save or publish of a post or page
  • Only counts Image blocks (including within Galleries), and skips if there are more than 100 images to check
  • Images already attached to another post or page are ignored
  • Once a post is published, only images added since the last save are attached, so as not to unintentionally re-attach images that have been detached from a post
  • Images in templates, template parts, and synced patterns are not affected
  • This behaviour is editor-only as it’s part of a UXUX User experience workflow, so posts saved via REST API, 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/ etc are not affected

The feature is automatically disabled for sites with attachment pages enabled (the wp_attachment_pages_enabled option). On such sites, changing the attachment parent changes the attachment’s URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org resulting in a 404 for the old URL, so the feature defaults to false.

For sites or plugins that wish to switch this feature on or off, the editor setting autoAttachMediaEnabled controls the behaviour. To turn it off, use the block_editor_settings_all filter:

add_filter( 'block_editor_settings_all', static function ( array $settings ): array {
    $settings['autoAttachMediaEnabled'] = false;
    return $settings;
} );

A site with attachment pages enabled can switch the feature on by setting the value above to true.

References

#7-2, #client-side-media, #dev-notes, #dev-notes-7-2, #media, #media-library

REST API changes in WordPress 7.2

WordPress 7.2 includes three 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/ changes. The first two change response and parameter shapes that existing code may depend on.

In short:

  • Revision and autosave responses no longer include 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. keys that are not revisioned. Plugins that write meta onto revisionsRevisions The WordPress revisions system stores a record of each saved draft or published update. The revision system allows you to see what changes were made in each revision by dragging a slider (or using the Next/Previous buttons). The display indicates what has changed in each revision. directly need to register those keys with revisions_enabled or add them with the wp_post_revision_meta_keys 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 comments endpoint’s status parameter is now an array. Code that compared $request['status'] to a string needs updating.
  • The new rest_allowed_cors_methods filter controls the Access-Control-Allow-Methods headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes., and a value set on a REST response is no longer discarded.

Revision and autosave responses only include revisioned meta

Visual Revisions 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 (new in 7.0) restores a revision by reading it from the REST API and saving its meta onto the post. Before 7.2, WP_REST_Revisions_Controller returned every show_in_rest meta key registered for the parent post type, read from the revision ID. Only revisioned keys are stored on a revision, so every other key came back as its registered default, or null when the default did not pass the key’s schema, and the restore wrote those values over the post’s real meta.

The visible effects were:

  • Restoring an unsynced pattern sent null for wp_pattern_sync_status, which deleted the status and made the pattern synced.
  • Restoring a synced pattern failed with a rest_invalid_stored_value error after the content had already been saved.
  • On other post types, non-revisioned show_in_rest keys were silently reset.

The classic revisions screen was never affected, because wp_restore_post_revision() only restores the keys from wp_post_revision_meta_keys(). The editor cannot tell which keys are revisioned, since revisions_enabled is not exposed over REST, so the fix had to happen in the endpoint (#66329).

What changed in 7.2

The new WP_REST_Revision_Meta_Fields class, a subclass of WP_REST_Post_Meta_Fields, limits a revision’s meta response and schema to the keys returned by wp_post_revision_meta_keys() for the parent post type. WP_REST_Revisions_Controller uses it for its $meta property. Keys registered with a custom show_in_rest name are handled the same way.

  • Autosave responses follow the same rules, because the revisions controller prepares them. Autosave requests are still validated against the parent post type’s meta schema, but only revisioned keys are stored, and only on an autosave revision. An author’s autosave of their own draft doesn’t store the meta it receives.
  • When an author autosaves their own draft, the autosaves controller updates the post itself and returns it instead of an autosave. That response still includes all of the post’s meta.
  • Anything returned by the wp_post_revision_meta_keys filter that is not a string is ignored.

What 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 should check

A meta key is revisioned when it is registered with revisions_enabled set to true, or when it is added with the wp_post_revision_meta_keys filter.

register_post_meta(
	'post',
	'my_meta',
	array(
		'show_in_rest'      => true,
		'single'            => true,
		'type'              => 'string',
		'revisions_enabled' => true,
	)
);

For meta registered elsewhere, or by code that cannot be changed, use the filter:

add_filter(
	'wp_post_revision_meta_keys',
	static function ( array $keys ): array {
		$keys[] = 'my_meta';
		return $keys;
	}
);
  • Plugins that write meta onto revisions directly, without either of the above, will no longer see those keys in REST revision and autosave responses. Adding the key to wp_post_revision_meta_keys brings it back, and also makes the key part of what the classic screen restores, so confirm that is wanted.
  • Clients that read revision meta over REST should expect non-revisioned keys to be absent rather than present with a default value. The meta schema for revisions shrinks to match.
  • When a post type has no revisioned meta, a revision’s meta is now an empty 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. array ([]) instead of an object holding each key’s default. 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 clients that read revision.meta.some_key get undefined either way, but code that checks the type of meta, or a PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher client that decodes it, will see an array.
  • Visual Revisions restores meta through the REST API, so a revisioned key also needs show_in_rest to be restored from the block editor. The classic revisions screen restores it either way (Gutenberg #85549).
  • Code that inspects the controller’s $meta property now finds a WP_REST_Revision_Meta_Fields instance. It still extends WP_REST_Post_Meta_Fields.

Sites running the GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ plugin on WordPress 7.0 and 7.1 get the same filtering from a compat change in Gutenberg (#85509), but the meta schema isn’t changed.

Related: r64731, #14359, Gutenberg #84809.

The comments endpoint accepts multiple statuses

The comments collection endpoint (/wp/v2/comments) now accepts several statuses in one request. WP_Comment_Query has always supported an array of statuses, but the endpoint only accepted a single string, so clients that needed comments in more than one status had to make a request for each (#63982).

/wp/v2/comments?status=approve,hold
/wp/v2/comments?status[]=approve&status[]=hold

Single status requests work as before, and so does the all status. The permission check is unchanged: users without the edit_posts capabilitycapability A capability is permission to perform one or more types of task. Checking if a user has a capability is performed by the current_user_can function. Each user of a WordPress site might have some permissions but not others, depending on their role. For example, users who have the Author role usually have permission to edit their own posts (the “edit_posts” capability), but not permission to edit other users’ posts (the “edit_others_posts” capability)., including unauthenticated requests, may only use the default approve status. Anything else, including a list that contains approve, is rejected with rest_forbidden_param.

What changed in 7.2

  • The status collection parameter is now an array of strings with a default of array( 'approve' ), and the route’s argument schema says so.
  • The new WP_REST_Comments_Controller::sanitize_comment_statuses() accepts a string, a comma-separated list or an array. It sanitizes each value with sanitize_key, removes duplicates and drops empty values. A literal 0 is kept, because held comments are stored with a comment_approved value of 0.
  • No enum of allowed values was added. WP_Comment_Query supports custom comment statuses, so an enum would have broken existing requests.

What plugin developers should check

After sanitization, $request['status'] is always an array, and so is status in the arguments passed to the rest_comment_query filter. Code that compared it to a string will no longer match:

// Before: only matches in 7.1 and earlier.
if ( 'hold' === $request['status'] ) {
	// ...
}

// After: works in 7.1 and in 7.2.
if ( in_array( 'hold', (array) $request['status'], true ) ) {
	// ...
}

Clients and tools that read the route’s argument schema will see status as an array rather than a string.

Related: r64494, #9870, Gutenberg #71271.

New rest_allowed_cors_methods filter

WordPress 7.2 adds a rest_allowed_cors_methods filter for the Access-Control-Allow-Methods header that the REST API sends with cross-origin (CORS) requests. It also stops discarding an Access-Control-Allow-Methods value set on a REST response (#46992).

The problem

When a request carries an Origin header, rest_send_cors_headers() sent a hardcoded list of methods: OPTIONS, GET, POST, PUT, PATCH, DELETE. The only ways to change it were to unhook rest_send_cors_headers() and re-implement it, or to call header() at a later priority. Both are fragile, and two plugins doing it will 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..

Setting the header on the response through rest_post_dispatch did not work either. rest_send_cors_headers() runs after the response’s own headers have been sent, and replaced whatever value the response set.

The two sibling CORS headers have had filters since 5.5: rest_exposed_cors_headers for Access-Control-Expose-Headers and rest_allowed_cors_headers for Access-Control-Allow-Headers. This filter fills in the third.

The new filter

rest_allowed_cors_methods follows the same shape as its siblings. It receives the list of methods as an array, along with the request in context, and the result is joined into the header. The request is null when rest_send_cors_headers() is called directly rather than while serving a REST request.

/**
 * @param string[]             $allow_methods The list of HTTP methods to allow.
 * @param WP_REST_Request|null $request       The request in context, if available.
 */
apply_filters( 'rest_allowed_cors_methods', $allow_methods, $request );

Callbacks should return an array, though coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. also accepts a comma-separated string such as 'OPTIONS, GET'. Because callbacks run in a chain, a callback can receive a string returned by an earlier one, so avoid an array type hint on $methods and normalize the value with wp_parse_list() before changing it.

Advertise an extra method, for example for a route that accepts PROPFIND:

add_filter(
	'rest_allowed_cors_methods',
	static function ( $methods ): array {
		$methods   = wp_parse_list( $methods );
		$methods[] = 'PROPFIND';
		return $methods;
	}
);

Narrow the list for cross-origin requests to a read-only namespace:

add_filter(
	'rest_allowed_cors_methods',
	static function ( $methods, ?WP_REST_Request $request ) {
		if ( $request && str_starts_with( $request->get_route(), '/my-plugin/v1/public' ) ) {
			return array( 'OPTIONS', 'GET' );
		}
		return $methods;
	},
	10,
	2
);

This is not a permission check. Access-Control-Allow-Methods only affects the preflight requests browsers send for some cross-origin requests. Simple cross-origin requests, such as a POST with a form content type, are not preflighted, and non-browser clients ignore the header. Use permission_callback on the route to restrict who can do what.

Returning an empty array omits the header entirely. Entries that are not valid 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. method tokens are dropped, an array entry such as 'GET, POST' is split into its methods, and a callback that returns something other than an array or a string is ignored in favor of the unfiltered list.

Response values are no longer discarded

If a response sets its own Access-Control-Allow-Methods header, for example from rest_post_dispatch, that value is now the starting list passed to the filter instead of being overwritten by the default:

add_filter(
	'rest_post_dispatch',
	static function ( WP_HTTP_Response $response ): WP_HTTP_Response {
		$response->header( 'Access-Control-Allow-Methods', 'OPTIONS, GET' );
		return $response;
	}
);

The filter still runs after that, so a site always has the last word. If the response value names no valid methods, the default list is used. With ?_envelope=1, the response’s headers are moved into the body before rest_send_cors_headers() runs, so a value set on the response is not seen and the filtered default is sent.

Backward compatibility

The default output is unchanged. A site that neither sets the header on a response nor uses the filter sends the same OPTIONS, GET, POST, PUT, PATCH, DELETE list as before.

rest_send_cors_headers() gains three optional parameters, $result, $request and $server, and is now hooked to rest_pre_serve_request with four accepted arguments. Existing calls with a single argument keep working, and remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' ) still removes it, since the priority is unchanged at 10. When serving a REST request, the CORS headers are now sent through WP_REST_Server::send_header() rather than a direct header() call.

Related: r64730, #13151, #57752 (the sibling filters gained the $request parameter in 6.3).

#7-2, #dev-notes, #dev-notes-7-2, #rest-api

Changes to the Interactivity API in WordPress 7.2

WordPress 7.2 brings three main changes to the Interactivity 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.. There’s a new data-wp-html directive to render HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. from the store, the router now tells you when a navigation is in progress and who started it, and three behaviors that were deprecated in previous versions have been removed.

New data-wp-html directive

data-wp-text sets the text of an element, but until now there was no equivalent for HTML. If a value in your store contained a description with links or some formatting, data-wp-text showed the markup as text, and the only alternative was to set innerHTML yourself from a data-wp-watch callback, outside of the Interactivity API rendering. That worked, but those changes could be overwritten by client-side navigation.

WordPress 7.2 adds the data-wp-html directive to fill that gap. It sets the inner HTML of an element, but only from values created with the new asDangerousHTML() function.

import { asDangerousHTML, store } from '@wordpress/interactivity';

const { state } = store( 'myPlugin', {
	actions: {
		*loadPreview() {
			const response = yield fetch( state.previewUrl );
			const html = yield response.text();
			state.preview = asDangerousHTML( html );
		},
	},
} );
<div data-wp-interactive="myPlugin">
	<button data-wp-on--click="actions.loadPreview">Show preview</button>
	<div data-wp-html="state.preview"></div>
</div>

Why asDangerousHTML()?

Rendering arbitrary HTML is a security concern, so data-wp-html never renders a plain string, by design. Values in the page’s markup, like the ones in data-wp-context, can come from content that 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. doesn’t fully control, and a string that ends up in the wrong place must not become HTML on the page. So the directive only renders values that your plugin’s 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 explicitly marked as trusted.

Keep in mind that asDangerousHTML() doesn’t sanitize anything. It’s the same responsibility that you take on when you use dangerouslySetInnerHTML in ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org. Passing untrusted input to it is an XSS risk, so never pass it raw user input, and never pass it a value read from context. The rule to follow is “context selects, state supplies”. Use context to choose which trusted HTML to show (an ID, or a flag), and build the HTML itself in state, from a source your plugin trusts.

The value that asDangerousHTML() returns is opaque, and it’s trusted because of its identity, not its content. If you copy it into data-wp-context, spread it into a new object or serialize it as JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML., the copy is not trusted anymore.

Which values render

The element follows the value of its reference.

  • A value returned by asDangerousHTML() renders its HTML.
  • null, undefined, or a path that doesn’t exist empty the element.
  • Anything else, including plain strings, empties the element and shows a warning in development mode (when SCRIPT_DEBUG is enabled).

There are two exceptions that keep the server-rendered content in place, which are explained in the server section below.

The content is inert to the Interactivity API

The content of a data-wp-html element is inert to the Interactivity API. The server doesn’t process the directives inside it, and in the browser they don’t run, the interactive regions inside it aren’t hydrated, and the router ignores the router regions inside it. This applies to the HTML inserted with asDangerousHTML() and also to the content that the element already had when the page loaded.

But “inert” only means inert to the Interactivity API. The content is still live HTML for the browser, so content that isn’t safe to render as HTML isn’t made safe by going through data-wp-html.

The directive can’t be combined with data-wp-text, data-wp-each or data-wp-router-region on the same element, because all of them want to own the content of the element. If you combine them, data-wp-html is ignored and you’ll see a warning in development mode.

Trusted Types

If your site enforces Trusted Types, asDangerousHTML() also accepts a TrustedHTML value created by your own policy, like asDangerousHTML( policy.createHTML( html ) ). The package doesn’t create a policy of its own. If the browser rejects a value, the element is emptied and you’ll see a warning in development mode.

Server-side rendering

The directive works on the server too. In PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher, mark the HTML as trusted with the new wp_interactivity_as_dangerous_html() function, and the server renders it inside the element during directive processing.

<?php
wp_interactivity_state(
	'myPlugin',
	array( 'preview' => wp_interactivity_as_dangerous_html( $html ) )
);
?>
<div data-wp-interactive="myPlugin">
	<div data-wp-html="state.preview"></div>
</div>

wp_interactivity_as_dangerous_html() doesn’t sanitize the HTML. In the cases where the browser shows a warning, the server triggers a _doing_it_wrong() notice.

The HTML is not included in the data that the server sends to the client. In its place, the server prints { "wpServerHtml": true }. When the client sees that value, it keeps the server-rendered content in place until the value changes, for example when your store sets a new asDangerousHTML() value.

Server-rendered content is also preserved when a derived state property is defined as a closure in PHP and its JavaScript getter hasn’t been registered yet. This keeps the content visible while the client-side module loads. Once the getter is available, data-wp-html follows its value using the rules described above.

See #83092, #84652, #84889, #84919 and #66246 for more details.

Props to @theaminuldev for the initial implementation, and to @darerodz, @santosguillamot and @luisherranz for the follow-ups and the server-side implementation.

Tracking client-side navigations

The WordPress 7.0 dev note deprecated state.navigation.hasStarted and state.navigation.hasFinished from the core/router store, and announced an official way to track navigations. That mechanism is now available in WordPress 7.2.

The core/router store has two new properties.

  • state.navigating is truthy while a client-side navigation is in progress.
  • state.initiator identifies who started the navigation. By default, it’s the ID of the closest router region that contains the element whose directive called actions.navigate(), or null when nobody identifiable started it, like in a back or forward navigation.

With them, a 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. can show its own loading indicator only when the navigation started inside it, which wasn’t possible before without workarounds. This is how it looks.

import { store } from '@wordpress/interactivity';

const { state: routerState } = store( 'core/router' );

store( 'myPlugin', {
	state: {
		get isLoading() {
			return (
				!! routerState.navigating &&
				routerState.initiator === 'myPlugin/quote'
			);
		},
	},
} );
<div data-wp-interactive="myPlugin" data-wp-router-region="myPlugin/quote">
	<span data-wp-class--is-loading="state.isLoading"></span>
	<!-- ... -->
</div>

You can also set the initiator yourself with the new initiator option of actions.navigate(). A string is used as it is, and null leaves the navigation without initiator.

yield actions.navigate( url, { initiator: 'myPlugin/cart' } );

There are a few things to keep in mind.

  • Both properties are undefined until the first client-side navigation, and on pages where the router never loads. So check them by truthiness (if ( state.navigating )) instead of comparing them with false or null.
  • state.navigating becomes false on a later frame than the one where the new content is added to the DOM, so a watcher that reacts to the end of the navigation sees the new page. Note that the promise returned by actions.navigate() resolves before that.
  • state.initiator is not cleared when the navigation ends. It keeps its value until the next navigation starts, so a watcher that reacts to the end can still know who started it.
  • They’re updated in every client-side navigation, including back and forward navigations served from the router’s cache. actions.prefetch() doesn’t count as a navigation.

state.navigation still works in WordPress 7.2, but it’s still deprecated and it will stop working in a future version. If you’re using state.navigation.hasStarted, you can replace it with state.navigating. There’s one difference, though. hasStarted was made for the loading bar, so it only became true after 400 milliseconds, and only when the loadingAnimation option was enabled. state.navigating is updated immediately, so if you don’t want to show a loading indicator on fast navigations, you’ll need to add that delay yourself.

You can find more examples, like how to move the focus after a navigation that started in a specific region, in the client-side navigation guide.

See #83280 for more details.

Props to @luisherranz for the implementation, and to @darerodz and @fabiankaegy for the reviews.

Removal of expired deprecations

Three behaviors that were deprecated in previous versions don’t work anymore in WordPress 7.2. If your blocks, plugins or themes use any of them, you’ll need to update your markup and stores.

Unique IDs with two hyphens

Unique IDs let you add several directives of the same type to the same element, and they are written after three hyphens, like data-wp-watch---id. Until now, the runtime also accepted two hyphens (data-wp-watch--id) with a deprecation warning. That form is not a unique ID anymore, and what happens now depends on the directive.

  • data-wp-watch, data-wp-init and data-wp-run don’t support suffixes, so the directive is skipped and its callback never runs. You’ll see a warning in development mode.
  • data-wp-on, data-wp-on-window and data-wp-on-document use the whole text after -- as the event name. So data-wp-on--click--counter now listens for an event called click--counter, and a click doesn’t run it. You’ll see a warning in development mode, but in production the handler just stops responding.

The deprecated data-wp-on-async directives are not affected by this change.

To migrate, add the missing hyphen.

<!-- Before -->
<div
	data-wp-init--setup="callbacks.setup"
	data-wp-watch--log="callbacks.log"
></div>
<button data-wp-on--click--counter="actions.count">Count</button>

<!-- After -->
<div
	data-wp-init---setup="callbacks.setup"
	data-wp-watch---log="callbacks.log"
></div>
<button data-wp-on--click---counter="actions.count">Count</button>

Since the event directives fail silently in production, it’s worth searching your code for them instead of waiting for a warning. These commands, run from the root of your project, should find most of the cases.

# Lifecycle directives with a suffix.
grep -rnE 'data-wp-(watch|init|run)--[^-]' .

# Event directives with a unique ID after two hyphens.
grep -rnE 'data-wp-on(-window|-document)?--[^ "=]*[^- "=]--[^-]' .

Negating a function

Until now, a directive value that started with ! and pointed to a function, like !actions.isEmpty, called the function and negated its result, with a deprecation warning. Now the function is not called, the value is undefined, and you’ll see a warning in development mode.

The solution is to use derived state, which you can negate as before.

const { state } = store( 'myPlugin', {
	state: {
		items: [],
		get isEmpty() {
			return state.items.length === 0;
		},
	},
} );
<div data-wp-interactive="myPlugin">
	<p data-wp-bind--hidden="!state.isEmpty">The list is empty.</p>
</div>

data-wp-ignore

The data-wp-ignore directive has been removed. An element with this attribute is now hydrated like any other element, so the directives inside it run, and you’ll see a warning in development mode. Please remove the attribute.

See #84098 for more details.

Props to @luisherranz for the implementation and to @darerodz for the review.

#7-2, #dev-notes, #dev-notes-7-2, #interactivity-api

Update bundled @wordpress/* packages and @wordpress/build to fix CSS module class name collisions

If your pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party. bundles its own copy of any package below, update to the listed version or later and release a new version of your plugin before WordPress 7.2.

PackageFirst version with the fix
@wordpress/ui0.26.0
@wordpress/dataviews22.0.0
@wordpress/admin-ui3.1.0
@wordpress/grid0.11.0
@wordpress/components*44.0.0

* If your plugin loads @wordpress/components through the wp-components script, WordPress 7.2 provides the fixed copy.

If your plugin compiles its own CSSCSS Cascading Style Sheets. modules with @wordpress/build, update to 0.27.0 or later and rebuild.

The problem

Some @wordpress/* packages are bundled into each plugin that uses them instead of being loaded once as shared scripts. A 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. in @wordpress/build, the tool that compiles these packages, made bundled copies of a package at different versions share CSS module class names. Class names were meant to change whenever the CSS that defines them changes, so that each copy’s styles apply only to its own components. Instead, they depended only on the file path and the class name. When two copies with different styles were loaded on one page, for example one in WordPress and another bundled in a plugin, each copy’s styles also applied to the other copy’s components. The result could match neither version, such as a focus ring appearing on every hovered tab (#85896).

This affects every version of these packages published before the fix.

What changes in WordPress 7.2

Starting with WordPress 7.2, class names change whenever the CSS that defines them changes (#85900). Two copies share class names only when their CSS is identical, so a copy with different styles no longer affects the other.

The packages that ship with WordPress 7.2 are built this way. A copy your plugin bundled from an earlier version no longer collides with them. However, two copies built before the change can still collide with each other, for example when two plugins on the same site bundle different older versions of @wordpress/ui.


Props to @aduth for review.

#7-2, #dev-notes, #dev-notes-7-2

The Secrets API in WordPress 7.2

Update 2026-11-17: The Secrets 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. will no longer be shipping with WordPress 7.2. See r65538 / WordPress/WordPress-Develop@53ea8006d1

Update 2026-11-13: Corrected the 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. migrationMigration Moving the code, database and media files for a website site from one server to another. Most typically done when changing hosting companies. steps for installs with more than one networknetwork (versus site, blog): each network’s root key has to be re-encrypted, not only the current network’s.

WordPress 7.2 adds the Secrets API, which stores credentials such as API keys and OAuth client secrets encrypted, with one previous version kept for rotation. The original design is in the proposal and the history is on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. #66187.

If you tested an earlier WordPress 7.2 beta or created a secrets.php drop-in, review the breaking changes since Beta 1 and beta migration instructions before upgrading.

Storing and reading a secret

$result = wp_set_secret( 'my-plugin/api-key', $api_key );

if ( is_wp_error( $result ) ) {
	// Nothing was stored. Keep the existing storage.
}

$secret = wp_get_secret( 'my-plugin/api-key' );

if ( $secret instanceof WP_Secret ) {
	$client->authenticate( $secret->reveal() );
} elseif ( null === $secret ) {
	// Never stored. Ask the user for it.
} else {
	// WP_Error: it exists but can't be read right now. Don't ask for a new one.
}

wp_get_secret() returns null only when the secret was never stored. When it exists but can’t be read, because the key or the database is unavailable, it returns a WP_Error. Keep the two apart: asking for a new credential on an error can replace one that still works.

Names take the form plugin-slug/secret-name, in lowercase letters, digits, hyphens and underscores. A name without a slash works but triggers _doing_it_wrong(). The prefix stops plugins from overwriting each other’s secrets. It isn’t access control, since any code running on the site can read any secret.

A name also cannot start or end with a hyphen or an underscore and only one slash is allowed.

WP_Secret shows [secret:my-plugin/api-key] when it is printed, logged, 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.-encoded, or passed to var_dump() or var_export(). Serializing or cloning it throws an exception. Only reveal() returns the value, so call it where you use the value, and don’t cache the object.

Writing a new value moves the current one to WP_Secret_Version::PREVIOUS, so you can fall back to it while a rotated credential rolls out. Saving the same value again, as a settings form does, keeps the previous version. wp_retire_secret_version() deletes it when you’re done.

The other functions:

  • wp_delete_secret().
  • wp_list_secrets() returns names and metadata, never values.
  • wp_import_option_as_secret() copies an existing option into a secret. It leaves the option for you to delete and flags the secret for rotation, since the old value has already been through your backups.
  • wp_set_network_secret() and the other *_network_secret() functions store secrets for a whole network on 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 and network functions never fall back to each other.

The functions don’t check capabilitiescapability A capability is permission to perform one or more types of task. Checking if a user has a capability is performed by the current_user_can function. Each user of a WordPress site might have some permissions but not others, depending on their role. For example, users who have the Author role usually have permission to edit their own posts (the “edit_posts” capability), but not permission to edit other users’ posts (the “edit_others_posts” capability)., because they have to work from cron and REST. Check them wherever a user enters or manages a value. The wp_secret_changed action fires when a secret is created, updated, imported, deleted, or retired. It passes fingerprints, never values.

Checking that the API is available

The API needs WP_SECRETS_KEY, covered in the next section. Before moving an existing credential into it, check:

if ( wp_is_secrets_api_available() ) {
	// Move the credential.
} else {
	// Keep the existing storage.
}

This returns false in three cases:

  • the secrets.php drop-in failed to load;
  • WP_SECRETS_KEY is missing or not usable;
  • the key can’t decrypt the root key that is already stored, which happens when someone changes the key after secrets are stored.

A keyring or provider from a working drop-in counts as available. If its backend fails on a request, that call returns a WP_Error.

Host-managed secrets

Some hosts provide secrets through a read-only provider, where values are managed in the host’s dashboard or CLICLI Command Line Interface. Terminal (Bash) in Mac, Command Prompt in Windows, or WP-CLI for WordPress. rather than in WordPress. On those sites wp_secrets_provider_is_writable() returns false and wp_set_secret() returns a WP_Error.

if ( ! wp_secrets_provider_is_writable() ) {
	// The host manages this secret. Show a notice instead of an input field.
	return;
}

$result = wp_set_secret( 'my-plugin/api-key', $api_key );

if ( is_wp_error( $result ) ) {
	// Show $result->get_error_message() to the admin.
	// Don't fall back to storing the value in an option.
}

Reads work the same on every provider, so wp_get_secret() needs no special handling.

Setting WP_SECRETS_KEY

Secrets are encrypted with libsodium (XChaCha20-Poly1305) and stored in the options tables. Their keys are derived from a random root key, which is stored encrypted with WP_SECRETS_KEY from wp-config.php.

Without a usable WP_SECRETS_KEY, the API stores nothing, and every write, and every read of a stored secret, returns a secret_key_unavailable error. An empty key, the wp-config-sample.php placeholder, or a value copied from one of the authentication keys or salts doesn’t count.

New installs get a key: the installer fills it in along with the salts. Existing sites need one added. Site Health generates a line to copy into wp-config.php, below the salts:

define( 'WP_SECRETS_KEY', '…a base64-encoded random 32-byte key…' );

You can also make one with php -r 'echo base64_encode( random_bytes( 32 ) ), "\n";'. Hosts and tools that write wp-config.php should add the key when they add the salts. 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/’s wp config create is being updated to do the same.

Don’t treat the key like the salts. Once secrets are stored, changing or removing it makes all of them unreadable until the old value comes back. To replace it, follow the steps in the last section.

Replacing the keyring, store or provider

A host can replace part of the API with a wp-content/secrets.php drop-in, which loads like db.php:

  • WP_Secrets_Keyring: keep the key that encrypts the root key in a KMS or HSM.
  • WP_Secrets_Store: keep the encrypted records outside the options tables.
  • WP_Secrets_Provider: hand the whole API to an external secret manager.
<?php
// wp-content/secrets.php

class My_Host_Keyring extends WP_Secrets_Keyring {
	public function wrap( #[\SensitiveParameter] string $key_material ) { /* … */ }
	public function unwrap( string $wrapped ) { /* … */ }
	public function get_key_source(): string { return 'My Host KMS'; }
}

$wp_secrets_keyring = new My_Host_Keyring();

The drop-in sets $wp_secrets_keyring, $wp_secrets_store or $wp_secrets_provider. If it fails to load, or sets one to the wrong type, every call returns an error and Site Health reports it. The API never falls back to the defaults, because a misconfigured backend shouldn’t look like an empty one.

PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 7.4 or higher doesn’t inherit attributes, so add #[\SensitiveParameter] yourself to any parameter that receives a key or a value. Conformance tests for keyrings and providers are in wordpress-develop under tests/phpunit/includes/secrets/.

Site Health

Three tests appear under Security:

  • Secrets API key source is recommended when the key is missing or not usable, and critical when it can’t decrypt the stored root key.
  • Secrets API: undecryptable secrets is critical when any stored secret can’t be decrypted.
  • Secrets API: credentials pending rotation is recommended when secrets are flagged, as imported ones are.

The Info tab has a Secrets API section with the provider, keyring, key source and the number of secrets.

In code, the tests are methods of WP_Site_Health, and the Info section is WP_Debug_Data::get_wp_secrets_api(), under the key wp-secrets-api (r65394). The wp_secrets_site_health_*() functions and the secrets-api key from the betas are gone.

Breaking changes since Beta 1

The following changes affect developers who tested earlier WordPress 7.2 betas or implemented custom drop-ins.

WP_SECRETS_KEY is required (r65385, r65389). In earlier betas, a site without it used a key derived from LOGGED_IN_KEY and LOGGED_IN_SALT, so rotating the salts made every secret unreadable. That fallback is gone. Secrets stored under it can be kept; see the next section.

The keyring, store and provider are abstract classes (r65390). They were interfaces, and an interface can’t gain a method without breaking every class that implements it. The method signatures are unchanged. Change implements to extends in your drop-in, and deployDeploy Launching code from a local development environment to the production web server, so that it's available to visitors. it together with 7.2. A drop-in that still says implements is a fatal error on every request, and the API can’t catch it.

Smaller changes during the beta:

  • Drop-ins can set the overrides as plain variables, not only through $GLOBALS (r65378).
  • secrets.php is listed with the other drop-ins on the Plugins screen and in Site Health (r65374).
  • Names with a trailing newline are rejected (r65375).
  • A failed database read no longer replaces the root key (r65373).

If you stored secrets during the beta

Secrets stored on a beta without WP_SECRETS_KEY are encrypted under the old fallback. After updating, Site Health reports that they can’t be decrypted. They’re still there. Leave the salts alone until you’ve finished these steps, because the old key comes from them.

  1. Generate a key with php -r 'echo base64_encode( random_bytes( 32 ) ), "\n";'. Add it and the old key to wp-config.php, below the salts:
    define( 'WP_SECRETS_KEY', '...your new key...' );
    define( 'WP_SECRETS_KEY_PREVIOUS', LOGGED_IN_KEY . LOGGED_IN_SALT );
  2. Re-encrypt the root key with the new key: wp eval '$r = ( new WP_Secrets_Key_Manager() )->rotate_site_key( new WP_Secrets_Config_Key_Provider( true ), new WP_Secrets_Config_Key_Provider() ); echo is_wp_error( $r ) ? $r->get_error_message() : "Done.";'
  3. Remove the WP_SECRETS_KEY_PREVIOUS line.

No stored secret is rewritten. On multisite, one run covers the current network. An install with more than one network has a root key for each, and each one needs re-encrypting before you remove WP_SECRETS_KEY_PREVIOUS. If you already added WP_SECRETS_KEY, keep it and add only the second line. The same steps replace any key: put the old value in WP_SECRETS_KEY_PREVIOUS.


Props to @whyisjake for technical review and @jeffpaul for copy review.

#7-2, #dev-notes, #dev-notes-7-2

Editor: The Options and View menus now use the new Menu component

WordPress 7.2 updates two menus in the editor headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes., Options (the “⋮” button) and View, to use the new Menu component from @wordpress/ui. The change applies to both the post and site editors.

The new menus have better keyboard navigation, proper checkbox and link items, and the same look as other components in the WordPress Design System.

For most plugins, things just work. You can keep using PluginMoreMenuItem, PluginSidebarMoreMenuItem, and PluginPreviewMenuItem. For action and link items, pass the label as children and use props such as icon, onClick, href, and disabled. For PluginSidebarMoreMenuItem, pass target to identify the sidebarSidebar A sidebar in WordPress is referred to a widget-ready area used by WordPress themes to display information that is not a part of the main content. It is not always a vertical column on the side. It can be a horizontal rectangle below or above the content area, footer, header, or any where in the theme., with icon and children as needed. The editor supplies the underlying menu item component.

import { registerPlugin } from '@wordpress/plugins';
import { PluginMoreMenuItem } from '@wordpress/editor';
import { external } from '@wordpress/icons';

function openMyTool() {
	// Handle menu item click.
}

function MyMenuItem() {
	return (
		<PluginMoreMenuItem icon={ external } onClick={ openMyTool }>
			Open my tool
		</PluginMoreMenuItem>
	);
}

registerPlugin( 'my-plugin', { render: MyMenuItem } );

There are a few changes worth knowing about:

  • 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. items in the Options menu now live in a new Panels submenu instead of a separate “Plugins” group (#82976).
  • The menu markup has changed. Styles or tests that target @wordpress/components class names, like .components-menu-item__button, won’t match anymore. In end-to-end tests, select items by role and name. Plugin items now sit in the Panels submenu, so tests must open Options, then Panels, before finding the item.

For example, after opening Options:

await page.getByRole( 'menuitem', { name: 'Panels', exact: true } ).click();
await page.getByRole( 'menuitemcheckbox', { name: 'Open my tool', exact: true } ).click();

Deprecated: as prop for plugin menu items

The as prop was never documented for these components. It worked only because they passed any extra props to the underlying ActionItem, which let plugins replace the menu item with their own component.

This no longer works with the new menu. @wordpress/ui is bundled into each package rather than shared, so each bundle has its 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 context. A plugin’s separately bundled Menu.Item can’t join the editor’s Menu.Root, so importing the new menu item directly isn’t a migrationMigration Moving the code, database and media files for a website site from one server to another. Most typically done when changing hosting companies. path. That’s why the editor now renders every item itself.

Starting with WordPress 7.2, PluginMoreMenuItem, PluginSidebarMoreMenuItem, and PluginPreviewMenuItem will ignore the as prop and display a deprecation warning:

The as prop of wp.editor.PluginMoreMenuItem is deprecated since version 7.2. Note: The menu renders the item itself. The prop is ignored.

The fix is to remove as and use the documented props instead.

// Before.
<PluginMoreMenuItem as={ MyCustomMenuItem } icon={ external } onClick={ openMyTool }>
	Open my tool
</PluginMoreMenuItem>

// After.
<PluginMoreMenuItem icon={ external } onClick={ openMyTool }>
	Open my tool
</PluginMoreMenuItem>

If the documented props don’t cover your use case, please open an issue and let us know what you need.

Direct users of ActionItem from @wordpress/interface can still supply as. In the editor’s Options and View menus, the compatibility adapter integrates that component with the new menu. The custom component must forward the supplied props and ref to its underlying DOM element. It retains its own markup and may need styling updates. Prefer PluginMoreMenuItem or PluginPreviewMenuItem where they cover the use case.

Please refer to the original pull requests for more details: #81564, #82321, and #82319.


Co-authored by @mamaduka and @mciampini

#7-2, #dev-notes, #dev-notes-7-2, #editor

New Block Support in WordPress 7.2: Text Shadow (textShadow)

WordPress 7.2 introduces a new textShadow typography 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. support, along with text shadow presets and a user interface in both the block inspector and Global Styles. The Paragraph and Heading blocks are the first coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. blocks to adopt it.

GitHubGitHub GitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged by the repository owner. https://github.com/ issue: #47904 | PR: #79584

Background

WordPress 7.1 added the ability to declare a text-shadow value under styles.typography in theme.json (#73320, see the Text Shadow Support in Global Styles 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.). That first step covered theme.json styling only. There was no control in the editor, no preset system, and no way to set a shadow on an individual block.

WordPress 7.2 builds on this foundation. Text shadows now work like font sizes and shadows: themes define presets, users pick or create them in Global Styles, and blocks that opt in get a control in the Typography panel.

How to opt in

In WordPress 7.2, the Paragraph (core/paragraph) and Heading (core/heading) blocks support text shadow by default. Other blocks can opt in through supports.typography.textShadow in their block.json:

{
	"supports": {
		"typography": {
			"textShadow": true
		}
	}
}

When a block declares support, a Text shadow control is added to the Typography panel of the block inspector, letting users choose from the predefined text shadow presets:

Text shadow control in the block sidebar with preset options

The control is not shown by default. Users can reveal it from the Typography panel’s options menu, or a block can show it automatically through __experimentalDefaultControls.

{
	"supports": {
		"typography": {
			"textShadow": true,
			"__experimentalDefaultControls": {
				"textShadow": true
			}
		}
	}
}

When a text shadow preset is applied to a block, its slug is stored in the textShadow attribute and output as a CSSCSS Cascading Style Sheets. class:

<!-- wp:paragraph {"textShadow":"strong"} -->
<p class="has-strong-text-shadow">Hello World</p>
<!-- /wp:paragraph -->

Defining presets

WordPress ships with two default text shadow presets, Light and Strong. Like font size and color presets, these can be managed in Global Styles (Typography > Text shadow presets), where users can change the styles of the default presets or add their own custom presets.

Text shadows panel in Global Styles

Themes can also define their own presets in theme.json with settings.typography.textShadowPresets. Each preset needs a name, a slug, and a textShadow value:

{
	"$schema": "https://schemas.wp.org/trunk/theme.json",
	"version": 3,
	"settings": {
		"typography": {
			"textShadowPresets": [
				{
					"name": "Soft",
					"slug": "soft",
					"textShadow": "1px 1px 2px rgba(0, 0, 0, 0.3)"
				},
				{
					"name": "Glow",
					"slug": "glow",
					"textShadow": "0 0 8px rgba(255, 215, 0, 0.8)"
				}
			]
		}
	}
}

Each preset outputs a --wp--preset--text-shadow--{slug} CSS custom property and a .has-{slug}-text-shadow class. Theme presets are shown alongside the default presets.

The Text shadow control lists all available presets and a None option. When there are 7 or more presets, it switches from a list to a compact dropdown.

The styles.typography.textShadow property introduced in WordPress 7.1 now also accepts a preset reference, such as var:preset|text-shadow|light. For more examples of applying text shadows globally, per block, or per element, see the Text Shadow Support in Global Styles dev note.

Values set in Global Styles override theme defaults, and values set on a block instance override both, following the same cascade as other typography styles.

Disabling text shadow

To hide the default presets, set defaultTextShadowPresets to false. To remove the feature entirely, also set textShadow to false:

{
	"version": 3,
	"settings": {
		"typography": {
			"textShadow": false,
			"defaultTextShadowPresets": false
		}
	}
}

Further reading

Props to @ramonopoly for review.

#7-2, #dev-notes, #dev-notes-7-2