Merge Proposal: Preferred Languages

Almost 8 years ago the Preferred Languages feature project was kicked off in response to a feature requestfeature request A feature request should generally begin the process in the ideas forum, on a mailing list, as a plugin, or brought to the attention of the core team, such as through scope meetings held for each major release. Unsolicited tickets of this variety are typically, therefore, discouraged. in #28197. Right now it is probably the oldest active feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins.. Over time there were numerous updates, 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, and even a complete refactor. Preferred Languages was always built and maintained with the goal in mind to merge it into coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. one day. Now the time is finally right to do so.

Purpose & Goals

As a quick reminder, Preferred Languages replaces the existing languages dropdown with a supercharged version that lets you select multiple preferred languages. WordPress then tries to load the translations for the first language that’s available, falling back to the next language in your list otherwise. Without this, WordPress would just fall back to English (US) in such cases, which is not a great experience. Such a UIUI User interface is a pretty standard feature that can be seen for example also in operating system and browser settings.

Preferred Languages UI, showing the list of selected languages on the settings page.
Example of the Preferred Languages UI on the settings page

Note: Preferred Languages works for both the site language (can be set at Settings -> General) and the user language (can be set in the profile).

Project Background

You may wonder why it took such a long time. Since the project’s inception, a lot has changed in WordPress. For example, 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/ happened. That’s why Preferred Languages saw a complete rewrite using the same ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/. components that also power 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. With Gutenberg we also saw the introduction of JavaScript localization, which required further iterations to Preferred Languages. Then there was a need for merging incomplete translations, reducing the chances that you see missing strings in English. However, merging translations was very bad for performance, as it involves loading lots of translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. files. In WordPress 6.5 we finally completely replaced the localization library with a more performant solution that natively supports loading multiple files at once. So this last remaining blockerblocker A bug which is so severe that it blocks a release. is now finally resolved!

Internationalization and localization is a core part of WordPress and relevant for more than half of all users. That’s why this functionality belongs natively into WordPress core and not in a (canonical) plugin. Merging Preferred Languages into core would allow the fallback logic to run much closer to where translation loading happens, reducing the risk for bugs 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 incompatibilities. Plus, the UI impact is minimal, as it simply expands an existing language dropdown with additional features.

Implementation Details

The UI is built using TypeScript and React and the @wordpress/* npm packages also used for Gutenberg. This makes for a consistent look & feel and will make it easy to integrate it into any revamped WordPress adminadmin (and super admin) UI. The back end parts were developed in such a way that merging them into core eventually is as straightforward as possible, so a patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. can be developed relatively quickly.

Preferred Languages has been tested in production websites over numerous years by thousands of users. It works in all major browsers supported by WordPress, follows accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) best practices, and gracefully falls back to the old single language dropdown if 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/. is disabled.

Contributors and Feedback

While I (@swissspidy) have been the lead developer of the plugin, valuable input and contributions have come from others in the community.

This is a proposal and is subject to revision based on your feedback. If you haven’t already tried out the plugin, please download and install it from WordPress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/ or the comfort of your WordPress admin. You can review the current code and leave feedback at the project’s GitHub repository or in #core-i18n on SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/..

All feedback will be collected over the next couple of weeks. After that, the received feedback will be discussed and next steps determined. The goal is to work on and land a patch quickly to ensure that the feature gets plenty of testing in WordPress trunktrunk A directory in Subversion containing the latest development code in preparation for the next major release cycle. If you are running "trunk", then you are on the latest revision..

Props to @ocean90 for reviewing this post.

#6-6, #feature-plugins, #feature-projects, #i18n, #merge-proposals, #polyglots, #preferred-languages

Merge Proposal: Rollback Auto-Update

Background

The biggest risk for a site owner when updating plugins is encountering a PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher fatal error that crashes their website. While CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. updates are protected by automatic rollbacks since WordPress 3.7 (#22704), no such protection for plugins was added. Although fatal error protection and recovery mode were added in WordPress 5.2, it requires manual intervention from an administrator, and ideally WordPress should be able to recover on its own in a similar way that Core does. The Upgrade/Install team began exploring rollbacks for 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 updates.

Rollbacks for plugin updates comprises three features:

  1. move_dir() – Introduced in WordPress 6.2 (#57375)
  2. Rollback for plugin/theme update failures when updating manually – Introduced in WordPress 6.3 (#51857)
  3. Rollback for plugin auto-updates when failures are encountered – Covered by this proposal (#58281)

Some background references

Overview

When active plugins are updated, they are briefly deactivated before the new version is installed and reactivated immediately after. Since WordPress 6.3, when an administrator is manually updating plugins, the plugin will not be reactivated if the update causes a PHP fatal error. During an auto-update, this reactivation check does not occur and the next time the site runs users will see the white screen of death (WSOD).

To further protect websites and increase confidence in automatic plugin updates within WordPress, the Rollback Auto-Update feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. aims to detect PHP fatal errors during automatic plugin updates, and subsequently rolls back to the previously installed version.

This proposal is to merge the changes required to also perform rollbacks when fatal errors occur during attempted plugin auto-updates by default.

Implementation

Rollback Auto-Update performs a loopback request to the homepage to check for PHP fatal errors, using an approach similar to the Plugin or Theme File Editors. If a PHP fatal error is encountered, an error handler logs the specific message and the previously installed version of the plugin is restored. When a plugin rollback occurs, a notification will be sent to the site’s administration email (stored in the admin_email option) notifying them of the failed update and rollback.

The current implementation attempts to detect a PHP fatal error during an automatic update by using a loopback request to the homepage. If the loopback returns an error, a PHP fatal error in the active plugin is assumed and the update will be reverted for safety.

After the problematic plugin is rolled back, the auto-updating process will continue for any other core, plugin, or theme updates that were in queue. When the next check for auto-updates occurs, WordPress will attempt to update the same plugin again.

Previously, maintenance mode was only enabled during installation of an update. However, testing established that disabling maintenance mode during the rest of the process means that active visits to the site can trigger errors. This can have side effects, such as deactivating plugins, etc. Rollback Auto-Update enables maintenance mode for the duration of all automatic updates. While maintenance mode is enabled for longer, this is relative to the number of updates being performed at that given time – usually a very low number – and helps improve stability of automatic updates.

At the time of publishing, this code is being tested on 6,000+ sites running the Rollback Update Failure feature plugin, which has contained the related code since v7.0.0 was released on 10/12/2023.

For easier testing of the feature within wordpress-develop, a merge PR (Core-5287) has been created.

Due to limitations in the ability to modify wp_is_maintenance_mode() in the feature plugin, the PR is slightly different. The feature plugin is available for historical reference. All pre-merge testing should be done using the PR. Some contributors have also been running the PR on sites for a few months.

Example of email text sent to site’s administration email.

Howdy! Plugins failed to update on your site at https://test.xxxxx.net.

Please check your site now. It’s possible that everything is working. If there are updates available, you should update.

The following plugins failed to update. If there was a fatal error in the update, the previously installed version has been restored.

  • This Plugin Should Not Be Used (from version 0.1 to 0.2) : https://wordpress.org/plugins/this-plugin-should-not-be-used/

To manage plugins on your site, visit the Plugins page: https://test.xxxxx.net/wp-admin/plugins.php

If you experience any issues or need support, the volunteers in the WordPress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/ support forums may be able to help.
https://wordpress.org/support/forums/

The WordPress Team

Testing

There are no known issues directly related to Rollback Auto-Update that don’t currently exist in Core.

I (@afragen) have been testing using the test plugin. The plugin is on a test site, active, and set to auto-update. I have been running like this since the beginning of the year using the PR and on other sites for several years using the feature plugin.

  1. Install the PR into WP 6.5.x or trunktrunk A directory in Subversion containing the latest development code in preparation for the next major release cycle. If you are running "trunk", then you are on the latest revision..
  2. Install version 0.1 of the test plugin.
  3. Activate the test plugin and enable auto-updates.

The WordPress.org update 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 serve the version 0.2 version of the plugin, which will cause a PHP fatal error. To confirm a rollback is successful, data is written to the error.log at every point in the auto-update process, creating an audit trail the user can use to discern the flow and results of rolling back an auto-update. This logging is only intended for testing purposes.

FAQ

Stay up to date with development on the PR. Please comment on the GitHub PR if any problems are discovered. 

  • What happens if loopback requests aren’t working?
    • As demonstrated by the Site Health message for loopback requests that aren’t working: “Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.” 
    • Auto-updates shouldn’t run if loopback requests aren’t working. If a loopback request fails due to an 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. error, Rollback Auto-Update will consider it as a PHP fatal error detected, and revert any plugin updates.

As a project, it’s important to continuously evaluate ways to make site management easier for the large majority of users and site owners. Providing safer plugin auto-updates is just one way for WordPress itself to handle problems that may require technical expertise seamlessly for end users.

All feedback will be collected and addressed over the next 2-3 weeks, with the goal of committing to trunk after all feedback is addressed to ensure that the feature gets plenty of testing through the nightly builds early in the WordPress 6.6 release cycle.

Props: @costdev and @desrosj for review and editing.

#6-6, #feature-projects, #feature-autoupdates, #merge-proposals, #rollback

Speculative Loading in WordPress

The WordPress Performance Team recently published a new plugin called “Speculative Loading” which enables a new technology of the same name to automatically prerender certain URLs on the page, which can lead to near-instant page load times. The functionality is powered by the Speculation Rules 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., a new web API that allows defining rules for which kinds of URLs to prefetch or prerender.

Please install and test the pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party to provide feedback to inform further improvements before a potential consideration to include such a feature in WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. You can install the plugin by searching “speculative loading” in WP Adminadmin (and super admin), or via the Performance Lab plugin.

A brief history of prefetch and prerender in WordPress

WordPress core has for several years provided a simple Resource Hints API which allows injecting <link> tags into the HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. document that can be used to prefetch or prerender certain resources, among other actions. While prefetching can be useful for certain sub-resources of an HTML document, such as third-party script providers, prerendering goes as far as processing the resource and already performing some rendering offscreen and thus can be useful for entire web pages.

However, using the approach of injecting link[rel="prefetch|prerender"] tags is not very flexible, as the URLs to prefetch or prerender need to be defined as soon as the HTML is loaded. Providing a <link> 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.) for every potential anchor link a user may click on the page would be wasteful, while not providing any misses a great opportunity for performance optimization. So far, solutions like Quicklink could be used to dynamically insert <link> tags to prefetch resources in the user’s viewport, which is more flexible, but still far from ideal as it may still excessively prefetch too many resources and requires a 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/. library.

More importantly though, link[rel="prerender"] does not actually support prerendering, as the “prerender” value is in fact used for something called NoState Prefetch, which means it is still only prefetching certain resources rather than prerendering them, which for instance would include running JavaScript. Last but not least, the “prerender” value is deprecated at this point.

Introducing the Speculation Rules API

The Speculation Rules API is a new web API that solves the above problems. It allows defining rules to dynamically prefetch and/or prerender URLs of certain structure based on user interaction, in 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. syntax—or in other words, speculatively preload those URLs before the navigation. This API can be used, for example, to prerender any links on a page whenever the user hovers over them. Also, with the Speculation Rules API, “prerender” actually means to prerender the entire page, including running JavaScript. This can lead to near-instant load times once the user clicks on the link as the page would have most likely already been loaded in its entirety. However that is only one of the possible configurations.

The following code example shows the general syntax of the Speculation Rules API JSON spec and outlines a configuration where any links other than WP Admin or login URLs are prerendered.

<script type="speculationrules">
{
	"prerender": [
		{
			"source": "document",
			"where": {
				"and": [
					{
						"href_matches": "/*"
					},
					{
						"not": {
							"href_matches": [
								"/wp-login.php",
								"/wp-admin/*"
							]
						}
					}
				]
			},
			"eagerness": "moderate"
		}
	]
}
</script>

The Speculation Rules API allows defining URL patterns for which kind of URLs should be eligible for speculative loading. Rules can be configured to either prefetch or prerender certain URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org patterns. A so-called “eagerness” value can also be specified which dictates how eagerly the prefetching or prerendering should be applied. For example, a value of “moderate” triggers the speculative loading when the user hovers over the link. A value of “conservative” delays this until the user clicks on the link (which still provides a decent performance benefit), while a value of “eager” acts as soon as there is the slightest suggestion a user may click the link. Note that caution is advised with the “eager” configuration in particular as it increases the likelihood of loading URLs wastefully.

Browser support

While the Speculation Rules API has been available in Chrome and Edge since version 109 in general, the particular subfeature needed to unlock the aforementioned functionality is called “document rules”, which was only recently added in version 121. This post describes the latest enhancements to the API in more depth.

In other words, at the time of writing this post end users will need to use either Chrome 121+ or Edge 121+ to get the benefits of this feature. However there are no adverse effects for users on other browsers, as this is a progressive enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature.. Therefore using the Speculation Rules API on your website is safe regardless of the user base.

The Speculation Rules API was presented at the W3C web standards conference TPAC 2023, with positive reception. At this point, the standard is in draft stage. Positions regarding the API by Firefox and Safari have been requested. To keep track of specifically the required subfeatures for the functionality outlined in this post, you can refer to this “Can I use” table.

The Speculative Loading WordPress plugin

As mentioned in the beginning of this post, the WordPress Performance Team recently published a new feature plugin “Speculative Loading” which enables speculative loading of other frontend URLs linked on the page. It inserts a JSON script similar to the previous code example. By default, any URLs linked on the page are prerendered with an eagerness configuration of “moderate”, which typically triggers when hovering over a link. As such, you don’t need to do anything after activating the plugin: it just works out of the box. The plugin also provides a few customization options to tweak the behavior to the site owner’s preference.

The Speculative Loading plugin’s settings UIUI User interface

The default behavior can be modified via a new “Speculative Loading” section in the Settings > Reading screen. For example, if the site is using JavaScript that is not yet adapted for being loaded while prerendering, the plugin could be configured to only prefetch documents. One could set the eagerness to “conservative” to reduce the likelihood of URLs being loaded without the user navigating to them. Or one could set it to “eager” to increase the chance of the speculative loading already being completed by the time the user lands on the linked URL, which however runs at the risk of wastefully loading several resources. The default of “moderate” strikes a good balance between sustainability and performance.

The rules for which kinds of URLs to speculatively preload can be customized using a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. called “plsr_speculation_rules_href_exclude_paths”. For example, plugins that add URLs to a WordPress site which modify user state just from being loaded could use that filter to exclude those URLs from being prerendered or prefetched. 

Here is a code example which would would ensure that URLs like https://example.com/cart/ or https://example.com/cart/foo/ would be excluded from prefetching and prerendering:

<?php

add_filter(
    'plsr_speculation_rules_href_exclude_paths',
    function ( $exclude_paths ) {
        $exclude_paths[] = '/cart/*';
        return $exclude_paths;
    }
);

Please refer to the plugin’s FAQ for details on the filter.

Potential next steps

At the moment, the plugin should be used to test the feature, and the Performance Team is eager to receive feedback as well as analyze the plugin’s performance benefits on load times.

Down the road, as the browser API and the plugin mature, the possibility of including the feature in WordPress core will be explored. However, in order to get there, additional feedback is needed.

Testing and feedback

Your testing and feedback is crucial to improve the feature ahead of exploring its potential usage in WordPress core. Please consider the following ways to help:

The WordPress performance team is excited to learn more about how the Speculation Rules API is being used in WordPress sites. Please try the plugin and share your feedback!

Props @adamsilverstein @domenicdenicola @jeremyroman @swissspidy @tunetheweb @tweetythierry @westonruter for review and proofreading.

#feature-projects, #performance, #performance-lab, #speculative-loading

Merge Announcement: Interactivity API

View the kickoff post, the status update post, and the Trac ticket for 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..

Purpose & Goals

Currently, 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 implement their chosen 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/. frameworks (or vanilla JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors.) to enhance user experiences on WordPress sites. There is no consistency or standardized pattern for developing frontend JavaScript in WordPress.

The Interactivity API provides a standard way for developers to add interactions into the frontend of their blocks.

The API has been designed and created with these requirements:

  • 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.-first and PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher-first. Prioritizing blocks for building sites and server side rendering for better SEO and performance. Combining the best for user and developer experience.
  • Backward compatible. Ensuring compatibility with both classic and block themes and optionally with other JavaScript frameworks, though it’s advised to use the API as the primary method. It also works with 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 internationalization.
  • Declarative and reactive. Utilizing declarative code to define interactions, listening for changes in data, and updating only relevant parts of the DOM accordingly.
  • Performant: Optimizing runtime performance to deliver a fast and lightweight user experience.
  • Send less JavaScript. Reduce the overall amount of JS being sent on the page by providing a common framework that blocks can reuse.  So the more that blocks leverage the Interactivity API, the less JS will be sent overall.

A live demo of what can be achieved was announced in the State of the WordState of the Word This is the annual report given by Matt Mullenweg, founder of WordPress at WordCamp US. It looks at what we’ve done, what we’re doing, and the future of WordPress. https://wordpress.tv/tag/state-of-the-word/..

Live site demo

In case you want to read more about the goals, you can refer to the initial proposal.

Project Background

The project started as an experimental plugin in early 2022. Then, the first API version debuted in Gutenberg 16.2 and has been continually refined until Gutenberg 17.7.

In WordPress 6.4,the Image, Search, File, Navigation, and Query coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. blocks were refactored using the private version of the Interactivity API, addressing accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) issues and adding the long-time expected lightbox (or “expand on click”) feature for images.

The development has been done in 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/, using a Tracking Issue to monitor progress and a Discussions category to solicit feedback and offer guidance to developers who assisted in testing.

Implementation Details

The Interactivity API is a standard system of directives, based on declarative code, for adding frontend interactivity to blocks.

Directives are special HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. attributes that tell the Interactivity API to attach a specified interaction to a DOM element or to transform it, similar to HTMX or AlpineJS. Using HTML as the templating language enables the API to understand the directives both in the server (PHP) and in the client (JS).

As part of this project, and all the interactivity scripts are now implemented leveraging the new script modules which are also shipping in WordPress 6.5. All of them will only be loaded on the frontend if at least one interactive block is present, to avoid sending unnecessary JavaScript to the frontend.

Here is an example of an interactive block, with a JavaScript file in charge of increasing or decreasing a counter, and a PHP file in charge of counter initialization and rendering.

// JS File - viewScriptModule.js

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

const { state } = store("my-counter-block", {
 actions: {
   increaseCounter: () => {
     state.counter = state.counter + 1;
   },
   decreaseCounter: () => {
     state.counter = state.counter - 1;
   },
 },
});
// PHP File - render.php
wp_interactivity_state('my-counter-block', array(
   'counter' => 0,
))
?>

<div
   <?php echo get_block_wrapper_attributes(); ?>
   data-wp-interactive="create-block"
>
   <button data-wp-on--click="actions.increaseCounter">
       <?php esc_html_e( 'Increase', 'my-first-interactive-block' ); ?>
   </button>
   <p data-wp-text="state.counter"></p>
   <button data-wp-on--click="actions.decreaseCounter">
       <?php esc_html_e( 'Decrease', 'my-first-interactive-block' ); ?>
   </button>
</div>

This would result in a block like this one:

For developers looking to get started, there is a Getting Started guide available, with plans to transition it to a handbook in the near future.

Additionally, a detailed 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. will be released, providing further insights into utilizing the API and understanding its internal workings.

Modules and Import maps.

The Interactivity API brings along the support of Modules and Import Maps.

JavaScript modules have transformed the way developers write and organize JavaScript code. They provide a cleaner and more modular architecture, making code easier to maintain, test and reuse across projects.

With the addition of native support for registering and enqueueing JavaScript modules, WordPress can keep pace with web development by using efficient, effective and battle-tested methods to handle JavaScript libraries and their dependencies.

There will be another dev note about JavaScript Modules and a guide to use them.

Guide to Javascript Modules.

Contributions and Feedback.

The Interactivity API is intended to be a long-term project with future enhancements; feedback is highly welcome. The best way to reach out is via GitHub Discussions.

Code and documentation contributions are also welcomed, and the Gutenberg repository is the place to go.

Some examples of contributing could be:

  • Test the Interactivity API, create your own interactions, and share feedback about what you like and you don’t.
  • Suggest new features to include in the API.
  • Help creating tutorials or share demos that can inspire other people.

Spread the word

The more developers who use Interactivity API in their projects, the more consistency there will be in the WordPress ecosystem, and the less JavaScript will be sent to the world!

Feel free to spread the word about the Interactivity API in social media and events with your colleagues, friends, and everyone!

Props to @cbringmann, @gziolo, @swissspidy, @westonruter, @santosguillamot, @luisherranz, and @rmartinezduque for peer review.

#6-5, #feature-plugins, #feature-projects, #interactivity-api, #merge-proposals

Merge Announcement: Plugin Dependencies

Note: This post was updated to add the “Third-party plugins not hosted on WordPress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/” section. 15th February, 2024 – @costdev

View the kickoff post, the Trac ticket and the feature plugin for 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 Dependencies.

Purpose & Goals

Extensibility of WordPress through plugins and the 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. 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. is one of its most beneficial features. There are many plugins that act purely as extensions of others, building functionality on top. The Plugin Dependencies feature aims to make the process of installing/activating addons (dependents) and the plugins they rely on (dependencies) consistent and easy to use.

Plugin authors are currently implementing their own ways of informing users about other plugins that they depend on. The implementations are inconsistent and sometimes incomplete. Users are often left to search for and install the other required plugins themselves.

The feature does not intend to replace the need for defensive coding within dependent plugins, or ensure version compatibility with their dependencies; nor does it seek to mitigate the vast array of potential plugin interactions. For WordPress and/or PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher incompatibilities, CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. already has handling for preventing installing, updating, or activating plugins with unmet requirements.

Implementation Details

A plugin’s dependencies can be declared by the use of a new Requires Plugins 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. in the dependent plugin’s main file. This must contain a comma-separated list of WordPress.org slugs for its dependencies, such as jetpack (jetpack/jetpack.php is not supported). It does not support commas in plugin slugs.

Example

/**
 * Plugin Name: Bridge for Foo and Bar
 * Requires Plugins: foo, bar
 */

Version management support, such as providing specific minimum and maximum version numbers through the Requires Plugins header value, is not currently supported.

Requirements

Declaring a plugin dependency places the following requirements:

  1. Bridge for Foo and Bar can only be installed once Foo and Bar have been installed.
  2. Bridge for Foo and Bar can only be activated once Foo and Bar have been activated.
  3. Foo and Bar can only be deactivated once Bridge for Foo and Bar has been deactivated.
  4. Foo and Bar can only be deleted once Bridge for Foo and Bar has been deleted.

Viewing, installing and activating dependencies

In the Plugins > Add New screen, dependencies are listed in the dependent’s plugin card. Next to these is a View Details link to open a dependency’s information modal. The dependency can be installed and activated using the buttons in the modal’s footer.

Previously, the modal would close upon clicking the Install Now or Activate button. The feature makes the modal persistent, and the buttons used in the plugin cards and modal now use the same underlying markup and functionality for consistency and reduced maintenance burden.

The side effect of this shared functionality is that automatic redirection upon activating a plugin from Plugins > Add New is no longer available. This has the benefit of not redirecting a user away from the Plugins > Add New screen for each plugin, removing them from their current context. Users can therefore install and activate multiple plugins without leaving their current context.

For plugins with onboarding experiences, they often have additional logic in case a plugin is installed and activated through a tool such as 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/, so that the user is still presented with the onboarding experience upon navigating to a screen deemed an appropriate starting place.

Automatic deactivation of dependent plugins

As currently implemented, plugins with unmet dependencies are automatically deactivated. While this was the approach suggested in initial discussions, there were valid concerns raised about this behavior after merging into trunk. These have been weighed and discussed, and a decision was made to remove this behavior.

Third-party plugins not hosted on WordPress.org

Defining plugins not hosted on WordPress.org as dependencies will enforce and display the dependencies to the user. However, there will be no ability to install the missing plugins through the UIUI User interface changes, and these will need to be installed manually.

UI changes

The feature makes changes to the UI on two screens: Plugins > Installed plugins, and Plugins > Add New.

Design Feedback

Design feedback was requested on the ticketticket Created for both bug reports and feature development on the bug tracker. and responses were received from @azaozz, @paaljoachim and @karmatosed on the ticket and on the Feature Plugin repository.

Plugins > Installed plugins

The following changes are made:

  1. Dependent plugin rows now contain a list of their dependencies, linked to the respective plugin modal to install and activate the dependency.
  2. Dependency plugin rows now contain a list of their dependents.
  3. If a plugin has dependencies that are not installed and active, the Activate link is disabled.
  4. If a plugin has dependents that are active, the Deactivate and Delete links are disabled.

Before

Plugin rows without listing any dependents or dependencies.
No dependents or dependencies are listed.

After

Plugin rows for a dependent and its two dependencies. The plugin row for a dependency shows a list of plugins that depend on it, and a dependent's plugin row shows a list of plugins that it depends on. The dependent's plugin row links the names of each dependency to a modal with buttons to install and activate the dependency.
Dependents and dependencies are listed, and actions are enabled/disabled based on the status of requirements.

Plugins > Add New

The following changes are made:

  1. If a plugin has unmet dependencies, the Install Now and Activate buttons are disabled, both in their plugin card and their plugin information modal.
  2. Dependent plugin cards now contain a notice listing their dependencies, with a View Details link to the dependency’s information modal which contains Install Now or Activate buttons based on their current installation status.
  3. Plugin information modals are now persistent after button clicks, and modal-based plugin installation and activation are now performed through AJAX directly within the modal.

Before

A plugin card that does not list dependencies for the plugin, and allows installation even if the dependencies are not installed first.
Plugin card with no dependencies listed and an active Install Now button despite unmet dependencies.

After

A plugin card with a notice containing a list of dependencies and a link to open a modal with buttons to install and activate the dependency
Plugin card with dependencies listed with modal links to install and activate each dependency, and the “Install Now” button disabled while dependencies are unmet.

User Testing

The feature team released calls for testing in October 2022 and March 2023. Additional user testing was performed during design and technical feedback with reports on the ticket and in the #core-upgrade-install SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel up to the day of commit.

Outcomes

Based on responses to calls for testing, and design and technical feedback, the following UI changes were made:

  1. Adminadmin (and super admin) notices for each unmet dependency were reduced to a single notice informing the user that there were plugins with unmet dependencies.
  2. A dedicated Dependencies tab was removed from the Plugins > Add New screen in favour of an integrated solution in plugin rows on Plugins > Installed plugins and plugin cards on Plugins > Add New.
  3. The plugin row on Plugins > Installed plugins had a Manage Dependencies action link removed, which linked to the removed Dependencies tab.
  4. Messaging was improved to inform the user about missing dependencies.

Security

A security review was performed by @costdev during the development of the feature following WordPress security best practices of escaping output, sanitizing input (slugs, POST, etc.), verifying AJAX referrers and using nonces where appropriate. Comparisons were also done with existing functionality to avoid missed opportunity for hardening the feature.

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

The feature was reviewed by the team for accessibility concerns. In addition, @costdev reached out to @joedolson regarding the use of links (<a>) as buttons, rather than <button> elements.

It was deemed that this approach, though likely not ideal, is consistent with the patterns throughout the code base today. A wider conversation is needed before a decision can be made about this specific  accessibility pattern at a later date.

wp.a11y.speak() is implemented where appropriate in JavascriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/., consistent with prior functionality in Core.

Unit Tests

In addition to user testing, testing by Core developers, and the feature team, unit tests have been written for the feature and the public API is covered. There are plans to continue increasing test coverage during the 6.5 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. period.

Props to @afragen, @pbiron, @azaozz and @desrosj for peer review.

#6-5, #feature-plugins, #feature-projects, #feature-plugin-dependencies, #merge-proposals

Preferred Languages: Help test the latest version

Since the last update on the Preferred Languages feature plugin, a lot of work has been accomplished both on the pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party side and in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. to make the solution more robust in a variety of ways. Today, I want to provide a bit more details on these accomplishments, which resulted in the recent release of Preferred Languages 2.0, advancing the project a huge step closer towards a core merge proposal

But first, make sure to check out the previous update:

Improved Stability, Fully Rewritten

Over the last year, a lot of work has gone into making the plugin more stable by adding more tests and fixing bugs. This includes improving compatibility with other plugins and making translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. merging and localeLocale A locale is a combination of language and regional dialect. Usually locales correspond to countries, as is the case with Portuguese (Portugal) and Portuguese (Brazil). Other examples of locales include Canadian English and U.S. English. switching more robust. As a result, pure unit testunit test Code written to test a small piece of code or functionality within a larger application. Everything from themes to WordPress core have a series of unit tests. Also see regression. code coverage is near 100%, with end-to-end tests adding another layer of confidence.

With WordPress adding several i18ni18n Internationalization, or the act of writing and preparing code to be fully translatable into other languages. Also see localization. Often written with a lowercase i so it is not confused with a lowercase L or the numeral 1. Often an acquired skill. improvements in WordPress 6.1 and 6.2, the Preferred Languages plugin is now fully compatible with WP_Textdomain_Registry and switch_to_user_locale(). The minimum required WordPress version has been bumped to 6.1 as a result.

Certainly the biggest change, however, was the full refactoring of the UIUI User interface itself. The whole 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/. portion of the code base was over 6 years old and using jQuery and jQuery UI. But not anymore! The UI has been completely refactored to use ReactReact React is a JavaScript library that makes it easy to reason about, construct, and maintain stateless and stateful user interfaces. https://reactjs.org/., with the same components that also power 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. In the process, drag & drop sorting functionality was removed to simplify the UI, and accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) has improved, but otherwise everything looks mostly the same.

How to help

So, what’s next? The latest version of the Preferred Languages feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. needs more eyes testing it and providing feedback.

One big remaining question mark is the concept of translation merging. By default, if there are only some missing strings in a selected locale, these would be displayed in English. But with translation merging, the missing strings will be taken from the locale next in line instead. While this works great, it could be a tad slow due to the way translations are loaded in WordPress. Any help addressing this potential performance concern would be greatly appreciated.

Note: The merging feature can be enabled with add_filter( 'preferred_languages_merge_translations', '__return_true' );.

Active development is taking place on GitHub. If you want to get involved, check out the open issues and join the #core-i18n channel on Slack.

Props to @ocean90 for reviewing this post.

#feature-plugins, #feature-projects, #i18n, #polyglots, #preferred-languages

Enhancing the Scripts API with a loading strategy

Overview

This post outlines a proposal to add a script loading strategy enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. to coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.’s existing Scripts 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..  

The underlying goal of this effort is to make it easier for WordPress pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and theme developers and core to use “modern” loading approaches for 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/. (like defer and async), which will help WordPress sites load faster and operate more smoothly, giving users a better experience.

Why add a loading strategy?

Data from the Web Almanac project (query) indicates that render blocking JavaScript is a significant problem on the web, with 77% of mobile pages having render-blocking scripts in the document <head> . This query shows that approximately 40% of WordPress sites stand to benefit from deferring additional scripts. Adding defer or async to script tags enables script loading without “blocking” the rest of the page load, resulting in more responsive sites overall better user experience.

Currently WordPress core as well as plugins and themes register scripts with the wp_enqueue_script and/or wp_register_script functions. Although these functions include the ability to control the placement of the script (with the in_footer parameter), they don’t include support for adding modern attributes such as defer or async to script tags. 

To add async or defer today, developers must resort to less flexible and more fragile approaches, such as directly filtering the tags at the point of output (using  the script_loader_tag 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.), or handling 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.) output directly using wp_print_script_tag and the wp_script_attributes filter.

Using the first approach and directly filtering the tag can easily break: for example if two plugins both try to filter a tag, or if a tag has unexpected attributes already (eg. adding defer to a tag that already has async). Using the the second approach developers must carefully handle dependencies and output manually – things that that the Scripts API usually helps take care of.

How the loading strategy works

Developers specify a loading strategy when registering or enqueueing a script. For example, a defer strategy can be specified when the script isn’t required immediately during the page load cycle. WordPress will then determine which scripts can actually use a strategy based on logic for each strategy. For example, to ensure that scripts are executed in the order they are enqueued, defer can only be used on a script if every script that depends on that script can also be deferred. Inline script tags added with wp_add_inline_script would also be considered to ensure proper execution order.

The implementation would come with several initial built-in loading strategies: defer, async, and the default blocking behavior.

Out of scope for this feature

The loading strategy does not enable direct control of script tag attributes. This idea was originally proposed 10 years ago in #22249 and several approaches were considered on that ticketticket Created for both bug reports and feature development on the bug tracker. including a script attribute filter. This proposal takes a step back and aims to solve the script loading strategy aspect more comprehensively and directly while avoiding exposing the potential complications of direct attribute control.

It is worth noting that it is already possible to control attributes on wp_enqueue_script tags directly using the script_loader_tag filter. However, this is a bit of a “brute force” approach which is limited and fragile because it doesn’t consider dependencies and multiple plugins can take conflicting actions on the same tag. 

What are potential concerns with this feature?

One big concern with adding this feature to the WordPress Script API is potentially introducing a breaking change. wp_enqueue_script is a fundamental API in WordPress core, and any breaking changes could have widespread implications. Possible breakage is a possible reason that adding custom attributes as proposed in #22249 was never added to core.

This new proposal aims to ensure that there is 100% backwards compatibility, resulting in zero risk of breakage. The loading strategy will ensure that all existing uses continue to function as expected; for example, passing the boolean in_footer attribute will still control script placement. In addition, it will ensure that scripts continue to be executed in the order they are enqueued – as described above in the “How the loading strategy works” section.

Conclusion and Next Steps

Giving developers the ability to specify a loading strategy will enable them to use more advanced JavaScript loading methods while still ensuring that enqueued scripts are executed in the correct order. A “strategy” approach is also forward thinking: as the web evolves, new strategies can be developed and made available to WordPress developers. After gathering feedback, we will proceed to discussing the implementation approach and, ultimately, proposing a patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing..

Have you tried using defer or async with WordPress (or do you already)? How do you think this enhancement would change that? Please leave your feedback about this proposal in the comments below and if you can, join us at our weekly performance team chats, where we are likely to discuss this proposal in the future.

Thanks to @flixos90, @tweetythierry and @mxbclang for help writing and reviewing this post and for the many contributors who have added to the discussion around this enhancement already.

#core, #feature-projects, #javascript, #performance, #proposal

Call for Testing: Plugin Dependencies

The Plugin Dependencies feature plugin is available for testing.

This feature allows 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 to identify which other plugins must be installed so that their plugin functions as expected. This is done by adding a “Requires Plugins” 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. to the docblockdocblock (phpdoc, xref, inline docs) of the main plugin file which contains a comma-separated list of slugs for the required plugins.

The feature is not intended to work with Must-Use plugins, nor does it impact them.

You can find out more about this feature project in the original Make post.

Test Setup

  • Install and activate the Plugin Dependencies feature plugin.
  • Delete the Hello Dolly plugin, a single file plugin cannot be a dependency
  • Copy the three test plugin files from /plugins/wp-plugin-dependencies/test-plugins to the /plugins directory.
  • Navigate to Plugins > Installed Plugins.

Test Instructions / Key Features

  • Confirm that a new adminadmin (and super admin) notice is displayed if there are additional plugins that must be installed if dependencies are missing.
  • Confirm that individual plugins with dependency relationships on Plugins > Installed Plugins display Requires or Required by: under the version information.
  • Add (install/activate) needed dependencies.
  • Confirm that admin notice goes away once all the dependencies have been installed. Dependencies don’t need to be activated for the admin notice to be satisfied and go away.
  • After installing all dependencies, confirm that the new admin notice disappears.
  • Confirm that the Deactivate link and checkbox are not available for plugins that are dependencies with active dependent plugins.
  • Once all dependent plugins are deactivated, confirm that plugin dependencies can then be deactivated and deleted.
  • Confirm that the Add Plugins > Dependencies page lists correct plugins, including non-WordPress.orgWordPress.org The community site where WordPress code is created and shared by the users. This is where you can download the source code for WordPress core, plugins and themes as well as the central location for community conversations and organization. https://wordpress.org/ plugins that are and aren’t supported.

Other Things to Test

  • In a test plugin, try to add a dependency using a plugin’s full name (not slug).
    • No dependency should be noted
  • Add a dependency for a non-wordpress.org plugin slug that is installed/active.
  • Hook the Plugins 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. to register a non-wordpress.org plugin.
    • This is done with the GitGit Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance. Most modern plugin and theme development is being done with this version control system. https://git-scm.com/. Updater plugin
  • Test adding “Requires Plugins” to the DocBlock of a plugin in mu-plugins.
    • Nothing should happen as mu-plugins are not supported for this feature.

What’s New?

In the main plugin file’s docblock:

  • A Requires Plugins header has been introduced.
  • List the slugs of the dependencies in a comma separated string. For example:

Requires Plugins: hello-dolly, akismet, wp-plugin-dependencies

On the Plugins admin page:

  • An admin notice informs site owners if there are additional plugins that must be installed. It will display as long as there are uninstalled dependencies.
  • Each plugin that requires other plugins has a new line in the plugin description. For example:

Requires: <dependency-1>, <dependency-2>, <dependency-3>

Required plugins that are available on wordpress.org are linked to their plugin page.

  • Each plugin required by other plugins has a new line in the plugin description. For example:

Required by: <dependent-1>, <dependent-2>, <dependent-3>

  • Each plugin that is a dependency, and is also dependent on other plugins, has both lines above.
  • If all the dependencies of a plugin have not been installed and activated then the dependent plugin will not be able to be activated.
Plugins page

On the Plugins > Add New > Dependencies tab:

  • The above Requires and Required by data will display in the plugin card.
  • This tab shows a card for each plugin that is required for other plugins to work.
  • Familiar Install Now, Activate and Active buttons are provided so that site owners can manage these plugins.
  • If a dependency is not available on wordpress.org and does not integrate with the Plugin Dependencies feature, it will not be possible to install or activate via this tab. The plugin will display in a generic card.
  • It is possible to integrate a dependency that is not available on wordpress.org with the Plugin Dependencies feature. This requires hooking into the plugins_api_request 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. and returning a valid plugins_api() response. This type of code was added to the feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. as a composer dependency with afragen/add-plugin-dependency-api, and a filter to the endpoint returning valid plugins_api() response for the Git Updater plugin. 
Plugin > Add New page

Instructions for Reporting Issues

Please leave feedback in the comments below this post.

If you find an issue:

Thanks for testing! Testing should be completed by December 1, 2022.

Thanks @costdev and @ironprogrammer for assistance.

+make.wordpress.org/test/

#call-for-testing, #core, #feature-plugins, #feature-projects

An Update on Preferred Languages

5 years after announcing the Preferred Languages feature project and implementing the first prototype, it’s time for a long overdue update on where things currently stand.

More than half of all WordPress sites in the world use a language other than US English. For these sites and users, the options to change the site and user language are great. But when there’s no translationtranslation The process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. for a given pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party or theme, WordPress falls back to US English. That’s a poor user experience for many non-English speakers.

The Preferred Languages plugin solves this issue by doing the same thing operating systems, browsers, and other types of software have been doing for years. It lets you select multiple preferred languages in your settings. WordPress then tries to load the translations for the first language that’s available, falling back to the next language in your list.

The Preferred Languages UIUI User interface

Recent New Features

After stabilizing the initial prototype, the feature pluginFeature Plugin A plugin that was created with the intention of eventually being proposed for inclusion in WordPress Core. See Features as Plugins. has lived a mostly dormant life, with only irregular updates here and there. Adding support for JavaScript i18n introduced in WordPress 5.0 was the biggest enhancementenhancement Enhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature.. With the plugin being stable and used on thousands of sites without issues, there was simply no need for any other change. Yet, the plugin was far from feature complete.

Over the past year, I blew the dust off and made significant improvements to the plugin:

  • Bringing UI and code up-to-date with latest WordPress version
  • Improved 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 support, bringing Preferred Languages to Networknetwork (versus site, blog) settings
  • Site Health integration
  • Increased test coverage
  • Improved compatibility with other plugins, especially those accessing the locale 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.
  • Added an option to merge incomplete translations to avoid fallbacks to US English

The latter is actually a pretty cool enhancement and can be enabled using a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.. Here’s what it does:

Let’s say your preferred languages are es_CR, es_MX, es_ES, en_US (in this order). With this feature, if some of the translations are incomplete, your site will be displayed in es_CR, with missing strings taken from es_MX, es_ES etc. Without this feature, missing strings would simply be displayed in US English straight away. Merging translations this way makes for a much better user experience.

What’s Still Missing / Open Questions

Textdomain Registry

Since the Preferred Languages feature plugin also needs to work well when switching locales, #39210 has been a missing feature for a long time. While the plugin has its own implementation of a textdomain registry originally created (but then reverted) in that ticketticket Created for both bug reports and feature development on the bug tracker., it is required for this change to finally land in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress..

My hope is that this can be implemented in WordPress 6.1+.

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/. Code Base

The initial version of the Preferred Languages plugin was built in a pre-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/ era, using jQuery and jQuery UI Sortable. It doesn’t make much sense to potentially merge such a new UI component into core that is built with those technologies.

Rather, some time should be spent to rebuild the client-side code. There are two possible options here:

  1. Rewrite in vanilla JavaScript, replacing jQuery with modern Web APIs. This is most feasible when removing the capability to sort languages using drag & drop, for which jQuery UI Sortable is currently used.

    If we’re okay with dropping drag & drop functionality, then this would be a straightforward change.
  2. Rewrite everything 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/.. A prototype of this actually exists, so it’s mostly a matter of finishing it up & perhaps submitting some upstream PRs to Gutenberg for any missing features.
    Using React would be more in line with current best practices and expansion of Gutenberg throughout WordPress adminadmin (and super admin). Such a rewrite would also facilitate potential use of the component directly within a Gutenberg context.
    On the other hand, it would significantly increase overall code size and thus maintenance burden, for little immediate benefit.

While I am currently heavily leaning towards the first option, inputs are always welcome!

Of course, if we are okay with keeping jQuery & jQuery UI Sortable, then no change is needed at all.

The Next Steps

The Preferred Languages feature plugin can always use help with development and testing. Right now resolving the two open questions is the main priority before proposing merging this functionality into core.

Active development is taking place on GitHub. If you want to get involved, check out open issues and join the #core-i18n channel on Slack.

#feature-plugins, #feature-projects, #i18n, #polyglots, #preferred-languages

Version 1.0.0 of the Performance Lab plugin published

The first stable version 1.0.0 of the Performance Lab 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 has been released. You can download it from the WordPress plugin repository or via GitHub.

The stable release means that the Performance Lab plugin’s infrastructure is now out of 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. testing stage. The plugin’s primary purpose remains to facilitate beta testing for future WordPress coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. performance features and enhancements, as outlined in the original plugin announcement post. The initial beta phase for the plugin was primarily to allow the performance team to discover early infrastructure bugs and fix them before the stable launch.

Included modules

The following modules are included in the 1.0.0 release:

  • WebP Uploads: Creates WebP versions for new JPEG image uploads if supported by the server. View related GitHub issues
  • WebP Support: Adds a WebP support check in Site Health status. View related GitHub issues
  • Persistent Object Cache Health Check: Adds a persistent object cache check for sites with non-trivial amounts of data in Site Health status. View related GitHub issues
  • Audit Autoloaded Options (experimental): Adds a check for autoloaded options in Site Health status. View related GitHub issues
  • Audit Enqueued Assets (experimental): Adds a CSSCSS Cascading Style Sheets. and JSJS JavaScript, a web scripting language typically executed in the browser. Often used for advanced user interfaces and behaviors. resource check in Site Health status. View related GitHub issues

Next steps

The performance team is going to continue enhancing the existing modules and evaluating additional modules to add in the future. The cadence and versioning strategy for upcoming releases is currently up for discussion. Please provide your feedback on plugin versioning in this issue if you are interested. There is an ongoing vote in that issue which is open until 2022-05-02 17:00 UTC.


Kudos to all the people that have contributed to and tested the Performance Lab plugin so far and made this first stable release possible! Let’s keep testing and iterating on the individual features to bring each of them closer to an eventual WordPress core merge.

Props to @mxbclang @adamsilverstein @jeffpaul for review and proofreading.

#feature-plugins, #feature-projects, #performance, #performance-lab