The WordPress coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. development team builds WordPress! Follow this site for general updates, status reports, and the occasional code debate. There’s lots of ways to contribute:
Found a bugbugA 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.?Create a ticket in the bug tracker.
WordPress multisitemultisiteUsed 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 introduces a new database table to store metadata associated with sites. This allows for the storage of arbitrary site data relevant in a multisite / networknetwork(versus site, blog) context.
Site metadata provides an alternative to using options and can be retrieved from multiple sites in a more performant way—without calling switch_to_blog(). Sites can now also be queried by their metaMetaMeta 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. with parameters supported by WP_Meta_Query.
The new wp_blogmeta table is a global table in WordPress and developers should be cautious not to overuse it. There is a trade-off between using site options and site metadata, so it is recommended to think about every piece of extra data associated with a site and how it should be stored.
Use options when the data concerns only the site itself. Using an option should continue to be the default approach for site data.
Use site metadata when the data also needs to be heavily used in the network context, especially when sites need to be queried by it.
A network update is required to install the new database table. The site meta APIAPIAn 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. includes a function is_site_meta_supported() to ensure no unexpected errors occur when that process has not run yet. As of WordPress 5.1, there is only a single use-case for the site meta in coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. which regards the fatal error protection mechanism (see #44458).
All of these functions are only available in multisite, however they work similarly to other metadata wrapper functions, such as for posts, terms, comments and users. In addition to these functions, it is now possible to use the common meta query arguments when querying sites with WP_Site_Query or its wrapper get_sites().
Note that the database table for site metadata is called wp_blogmeta. This is because wp_sitemeta is already used for another database table, and furthermore the new name works consistently alongside the related wp_blogs table that stores the most essential site data. The API exposed and described here uses the correct term “site”.
For background information on these changes, see #37923 and #40229.
An additional under-the-hood change related to this is that the metadata API is now loaded earlier in the WordPress bootstrap process so that it is available as early as the multisite bootstrap code. See #40948 for more information.
WordPress 5.1 sees a number of developer focused changes to the Cron APIAPIAn 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.. These changes were discussed and made in #21072, #32656, #45797, and #45976.
Meaningful return values
Prior to WordPress 5.1, the functions used to modify scheduled tasks would return ambiguous values. These now return values indicating whether the function call was successful or otherwise.
wp_schedule_single_event(), wp_schedule_event(), wp_reschedule_event() and wp_unschedule_event() each return true or false to indicate whether the cron schedule was successfully modified.
wp_clear_scheduled_hook() and wp_unschedule_hook() each return false if the update was unsuccessful, 0 if there were no events to unschedule or an integer indicating the number of events that were successfully deleted.
Return values have also been added to the functions predominantly for use by WordPress CoreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. only: spawn_cron(), wp_cron(), and _set_cron_array().
New Functions
Two new functions have been added to assist with returning data.
wp_get_ready_cron_jobs(): retrieve cron jobs ready to be run.
Returns the results of _get_cron_array() limited to events ready to be run, ie, with a timestamp in the past. The new function returns the data only, it does not cause them to be run; that remains the role of other functions.
WordPress Core stores all cron events as an array in a single option. As the number of events increases, this method of storage can become somewhat unwieldy and unperformant.
In WordPress 5.1 writing a custom storage system for cron events will become substantially easier with filters added to each of the functions used for scheduling, re-scheduling, cancelling and returning a list of events.
Each of these hooksHooksIn 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. follows the pattern of bypassing the Core function if the filterFilterFilters 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. returns a value other than null.
Unless you are writing your own system for storing Cron jobs, these hooks are best left unused. If you are writing a custom storage solution, you will need to use all of them.
Each hook can be used to hijack the following:
pre_schedule_event for both single and recurring events,
pre_reschedule_event for rescheduling an event,
pre_unschedule_event for unscheduling an event
pre_clear_scheduled_hook for unscheduling all events attached to a hook/argument combination
pre_unschedule_hook for unscheduling all events related to a hook
pre_get_scheduled_event for returning an event including by specifying its timestamp,
pre_get_ready_cron_jobs for returning all cron events that are ready to be run
Warning: Adding code to these hooks must be done very early, before any other plugins attempt to register cron events or WordPress attempts to run any scheduled cron events on the init action.
Therefore, it is recommended you run add_filter() as your pluginPluginA 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 is included , rather than waiting for the plugins_loaded or muplugins_loaded actions to fire. For example:
// File name: my-cron-plugin/my-cron-plugin.php
// Bootstrap immediately.
add_filter( 'pre_schedule_event', 'mcp_schedule_event', 10, 2 );
/**
* Use custom storage solution for scheduling Cron jobs.
*/
function mcp_schedule_event( $hijack, $event ) {
if ( $hijack !== null ) {
// Already hijacked.
return $hijack;
}
// Use my plugin's custom storage solution.
return true; // or false.
}
Note: WordPress 5.1 BetaBetaA 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. 1 and 2 included the filters pre_next_scheduled and next_scheduled in the function wp_next_scheduled(). These were later removed as the logic for returning the next scheduled event was moved to wp_get_scheduled_event() to improve performance.
In WordPress 5.1, a handful of small developer-focused changes were made that deserve to be called out. Let’s take a look!
File Path Value For WP_DEBUG_LOG
WP_DEBUG_LOG is a constant that tells WordPress to enable or disable error logging. Its default value is false (no error logging). But, if it’s defined as true (or 1) in the wp-config.php file, site errors will be logged in the wp-content/debug.log file.
Starting in WordPress 5.1, WP_DEBUG_LOG will also accept a file path as a value allowing a custom error log to be defined. For example:
When running PHPUnit tests, the WordPress test suite requires a wp-tests-config.php file to be present in order to run correctly. This file provides information similar to that provided by the wp-config.php file. This includes database information, site domain and title, etc. (see the wp-tests-config-sample.php file for more information). However, the test suite bootstrap file requires this file to be in one of two locations: the test directory (tests/phpunit), or the root of the develop repository.
Starting in WordPress 5.1, the WP_TESTS_CONFIG_FILE_PATH constant can now be added to the phpunit.xml configuration file to define a custom location for the wp-tests-config.php file.
New PluginPluginA 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 Action HooksHooksIn 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.
In WordPress CoreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress. today, the plugins_loaded, network_plugins_loaded, and muplugins_loaded action hooks exist, but these hooks are only run after all plugins of their respective types have been loaded. There is no easy way to execute arbitrary code between each plugin being loaded or only after plugin X is loaded.
This makes it difficult for developers to conduct performance monitoring and debugging during this stage of the loading process. In WordPress 5.1, the following action hooks will be added:
plugin_loaded
network_plugin_loaded
mu_plugin_loaded
These hooks will fire after every plugin is loaded. Each action hook will pass one argument, the full path of the main plugin file.
Because these hooks are fired after every individual plugin is loaded, they are not recommended as a replacement for plugins_loaded. Using them in this manner will cause issues with performance.
Short Circuit FilterFilterFilters 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. for wp_unique_post_slug()
When a post is created or updated, wp_unique_post_slug() is used to ensure that the post slug (post_name field) is unique to that post. By default, the function will add a numeric suffix to the desired post_name value and increment until a unique value is created (desired-slug-2, desired-slug-3, etc.).
In some scenarios (when post titles are the same and no post_name values are provided, for example), this can result in a performance bottleneck because a new query is performed every time the suffix is incremented until a unique value is created.
To help with this scenario, the pre_wp_unique_post_slug filter has been added in WordPress 5.1. If a non-null value is returned, the function will return that value and skip the default logic in the function. The new filter also opens the door for a handful of other use cases, such as always replacing certain terms in post names (changing wp to wordpress, for example).
wp_debug_backtrace_summary() (which returns a list of functions called to get to the current point in the code) will now correctly capture hook names for do_action_ref_array() and apply_filters_ref_array() calls (see #43488). Previously, only do_action() and apply_filters() were captured.
$wpdb->queries logs the elapsed time for each query but lacks the starting time. This has been added in 5.1 (see #43315).
The WP_Error class now has a has_errors() method, which returns a boolean value indicating if an instance contains errors. This adds consistency to code that has previously checked for errors in a variety of ways, such as if ( $error->get_error_code() ) and if ( empty( $error->errors ) ) (see #42742).
WordPress 5.1 introduces limited LIKEsupport for metaMetaMeta 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 when using WP_Meta_Query. The new compare_key parameter (meta_compare_key as a top-level WP_Query query arg) accepts a value of LIKE in addition to the default =. See #42409 and [42768]. Here’s an example of how the new parameter is used:
This will generate a query of the form ... AND meta_key LIKE '%foo%' ....
This enhancementenhancementEnhancements are simple improvements to WordPress, such as the addition of a hook, a new feature, or an improvement to an existing feature. follows from changes in WordPress 4.8.3 to the way that MySQLMySQLMySQL is a relational database management system. A database is a structured collection of data where content, configuration and other options are stored. https://www.mysql.com/. wildcard characters are handled when building queries. The changes in 4.8.3 broke compatibility for some plugins that passed wildcards into the key parameter of meta queries. The new compare_keyfeature in WP 5.1 is not a full replacement for the previous behavior, but it should allow for most use cases. See #43445 for discussion.
WordPress 5.1 will feature a new parameter for register_taxonomy(), 'meta_box_sanitize_cb', which increases flexibility when using coreCoreCore is the set of software required to run WordPress. The Core Development Team builds WordPress.UIUIUser interface for custom taxonomies.
Custom taxonomies can specify which metaboxMetaboxA post metabox is a draggable box shown on the post editing screen. Its purpose is to allow the user to select or enter information in addition to the main post content. This information should be related to the post in some way. UI they’d like to use in the Classic Editor by providing a meta_box_cb parameter when registering their taxonomies. This meant, for example, that a hierarchical taxonomyTaxonomyA taxonomy is a way to group things together. In WordPress, some common taxonomies are category, link, tag, or post format. https://codex.wordpress.org/Taxonomies#Default_Taxonomies. can choose to use the post_tags_meta_box() UI instead of post_categories_meta_box(), which is the default. Prior to 5.1, this customization wasn’t fully functional; while the UI could be swapped out in this way, the data submitted when saving posts was always processed according to whether the taxonomy was registered as hierarchical. This led to scenarios where custom taxonomy values weren’t properly parsed when saving a post.
In 5.1, this behavior is changed in the following ways:
The POST controller logic that was previously hardcoded in edit_post() has been abstracted into the new taxonomy_meta_box_sanitize_cb_checkboxes()and taxonomy_meta_box_sanitize_cb_input()functions.
WP will try to select an appropriate _sanitize_ callback based on the meta_box_cbassociated with the taxonomy. This will fix the underlying bugbugA 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. for existing taxonomies.
Developers who need more control over the processing of their metabox data can provide a custom meta_box_sanitize_cb when registering their taxonomies.
WordPress 5.1 introduces new short circuit filters to WP_User_Query and count_users().
The users_pre_queryfilterFilterFilters 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. was introduced in #44373 and runs before the database query takes place. This enables short-circuiting the database query entirely to return custom results. Returning a non-null value from the filter will bypass WordPress’s default user query (similar to the posts_pre_query filter for WP_Query added in #36687).
Developers should note that filtering functions that require pagination information are encouraged to set the total_users property of the WP_User_Query object (which is passed to the filter by reference). If WP_User_Query does not perform a database query, it will not have enough information to generate these values itself.
Using the users_pre_query Filter
Below is a rough example of how a pluginPluginA 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 can use the filter to replace the default behavior of WP_User_Query with a call to a remote data store.
Similar to posts_pre_query, callbacks must be careful about fields – the external APIAPIAn 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. may have to return user IDs or quasi-WP_User objects, depending on the value of fields.
A more in-depth example of how this filter can be utilized can be found in this project, which enables user query caching.
Filtering the count_users() Function
In addition, a pre_count_users filter was added in #43693 which enables short-circuiting the count_users function before the database query takes place. Returning a non-null value from the filter will bypass the default queries.
Using the pre_count_users Filter
Here is a sample code snippet showing how to use this filter:
A short circuit for WP_Site_Query and WP_Network_Query with a plan to add a sites_pre_query filter (#45749).
A short circuit for WP_Term_Query with a plan to add a terms_pre_query filter (#41246).
Why Add These Filters?
These query pre-filters enable plugins to use an alternate database store for queries, for example returning results from an external service such as an Elasticsearch server. The process started with the main post query, and these are now being expanded that to other queries in WordPress.
In WordPress 5.1, the new human_readable_duration function will be introduced. This function accepts a duration in hours, minutes and seconds and returns a “human readable” string appropriate for screen readers.
The function takes a string representing a time duration, with hours, minutes and seconds separated by a : (colon). For example, calling human_readable_duration( '3:10' ); will return 3 minutes, 10 seconds. Minutes and seconds are required. For 10 seconds, the call would be human_readable_duration( '0:10' );.
This new function was added as part of the work to improve the display of media metadata in #39667 where, in addition to adding units, aria-labels with plain language descriptions were added to improve accessibilityAccessibilityAccessibility (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):
Update (2019-03-04): The fatal error protection mechanism explained here has been pulled out of the 5.1 release as it had several flaws critical enough to postpone the feature. A new path to address the issues is underway via #46130 and is intended to be released as part of WordPress 5.2.
Update (2019-01-21): A few critical naming changes have been made regarding the fatal error protection since the post was originally published. Most importantly, the drop-in to override the new shutdown handler is now called fatal-error-handler.php, and the class to override is called WP_Fatal_Error_Handler. Furthermore, a new WP_DISABLE_FATAL_ERROR_HANDLER constant allows entirely disabling the feature via wp-config.php. The rest of the post is also updated to use these new terms, however you might need to update your code if you built anything based on the previous information. For a history of what exactly has changed since the original post date, please refer to the umbrella ticket #44458.
WordPress 5.1 will start showing notices to administrators of sites that run on long outdated PHPPHPThe web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher versions. This part of the Servehappy and more globally Site Health projects paves the way to a more secure and performant web and, more specifically to WordPress, to a bump of the minimum required PHP version.
The current threshold for which PHP versions to display the notice will be anything below 5.6. While the lowest PHP version still receiving security updates is currently 7.1, the idea is to not go all the way there at the beginning to limit the support load. PHP 5.6 is the intended version to bump WordPress requirements to, and from then the threshold for the PHP notice will increase granularly, with the goal to over time catch up with the actual PHP version progress. The threshold is managed via a new Servehappy APIAPIAn 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. endpoint on wordpress.orgWordPress.orgThe 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/, so the version numbers can be modified independently of a WordPress release.
The link from the button points to a new support page about updating PHP which briefly explains the problem and then dives into how to prepare for an update and perform it. The link URLURLA specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org in WordPress is a translatable string so that locales can provide their own versions of the page. In order for that process to be straightforward, the content is managed through a page template, with the translationtranslationThe process (or result) of changing text, words, and display formatting to support another language. Also see localization, internationalization. strings thus being available in GlotPress (see https://meta.trac.wordpress.org/ticket/4004). Furthermore, the link can be adjusted via either an environment variable WP_UPDATE_PHP_URL intended for hosting providers or a filterFilterFilters 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.wp_update_php_url for a more dynamic approach on the code level. Replacing the URL should happen in cases where a more specific guide to update PHP on the given environment exists. The hosting provider is the preferred source to set this, so plugins are recommended to honor this priority and not unconditionally override it. Furthermore, if the URL is changed in any way, the URL to the original WordPress resource is still maintained as an additional link, which you can see in the following screenshot:
For further background information on these changes, please refer to the respective tickets #41191 and #45686.
Fatal Error Protection
To help the process of recovering errors that result from updating the PHP version, a mechanism has been implemented to detect fatal errors and, in certain designated areas of WordPress, recover from them. While updating PHP is mostly fairly straightforward and popular plugins and themes are typically maintained well, not necessarily all extensions are compatible with the latest PHP versions yet. So unfortunately there might be cases where a pluginPluginA 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 causes the WordPress site to no longer be accessible after the PHP update by causing a fatal error.
With the so-called WSOD protection (white-screen-of-death protection), WordPress will recognize when a fatal error occurs and which plugin or theme is causing it. When accessing the adminadmin(and super admin) backend, the respective extension will be paused, allowing users to still log in to their site so that they can (at least temporarily) fix the problem. Once the extension is known to be fixed, it can be resumed from the backend. While this does not necessarily make updating PHP easier, it lowers the burden of possibly running into the case where you are completely locked out of your site when you do not have access to the codebase.
Extensions are only paused in the admin backend and a few other areas while for example the frontend stays unaffected, and thus broken. Since it is impossible to predict which functionality the broken extension is responsible for, it would be dangerous to have it disabled in the frontend. It is more clear to a user accessing the site to see a message that it is currently not accessible rather than, without notice, no longer having access to a certain part of the key functionality. In the frontend, a message that the site is currently inaccessible will be displayed via a regular wp_die() call, with a link to the admin backend. Sites that would like to modify this output can use a new php-error.php drop-in that should send the necessary HTTPHTTPHTTP 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.headerHeaderThe 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. as well as the output.
Note that, while the primary reason for implementing the fatal error protection mechanism was making the process of updating PHP less “dangerous”, it is technically not tied to the update at all. In fact, it will be enabled permanently and discover fatal errors under any circumstances.
For sites that prefer to alter this behavior or sites that would like to omit the WSOD protection altogether, it is possible to add a new drop-in file fatal-error-handler.php. That file should declare a custom shutdown handler class for treating fatal errors that extends the default WP_Fatal_Error_Handler, and then return the instance of it to use. The default class’s functionality is split into distinct methods so that it is easy to reuse and override as granularly as necessary in a child class. The functionality can also be disabled entirely if that is preferred, via a new constant WP_DISABLE_FATAL_ERROR_HANDLER or, more dynamically, a corresponding wp_fatal_error_handler_enabled filter.
For further background information on these changes, please refer to #44458.
Honoring Plugin PHP Version Requirements
When browsing plugins to install, WordPress 5.1 will display a warning for those plugins that require a higher PHP version than the one currently active. While that screen previously already included such information about WordPress version compatibility, it now does the same for PHP. Furthermore, for both of these potential issues, WordPress will now enforce these requirements, disabling the button to install such plugins.
This is only a first step in enforcing version requirements of plugins and themes. In a future WordPress version, these restrictions will expand also to updating or activating plugins and eventually cover themes as well.
For further background information on these changes, please refer to #43986.
In WordPress 5.1 the adminadmin(and super admin) table pagination links have had their CSSCSSCascading Style Sheets. styling modified.
This CSS change improves the color contrast ratio for better accessibilityAccessibilityAccessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) and improves consistency across the admin screens. The pagination links are now styled like the standard WordPress buttons. By default, they have a lighter background color. The background color will no longer change to blue on hover and focus.
Plugins and themes should not be affected by this change unless they are re-using the .tablenav and .tablenav-pages CSS classes. All pluginPluginA 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 should verify that this change does not affect them.
You can read more information about this change in the related TracTracAn open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress.ticketticketCreated for both bug reports and feature development on the bug tracker., #41858
Edit: On January 14, 2019, the Good and Bad Practices section was added to show both correct and incorrect code examples.
Starting in WordPress 5.1, if register_rest_route() is not called on the rest_api_init action hook, a “doing it wrong” notice will be triggered. This notice is being added in an effort to encourage best practices when registering REST APIREST APIThe 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/. endpoints.
First, let’s look at what happens when WordPress loads to set up the REST API and explore a few reasons why this pattern is beneficial.
REST API Bootstrap Process
WordPress does its best to ensure that the REST API is only loaded when a REST request is being performed. To do this, the rest_api_loaded() function is run on the parse_request action and checks for a value in the rest_route query argument. This argument is populated with a value when the Rewrite APIAPIAn 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. matches a WordPress REST API URLURLA specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org. When a value is present, the rest_get_server() function is called to instantiate the WP_REST_Server class, store it for use across WordPress, and to run the rest_api_init action hook.
Performance
When register_rest_route() is called, it invokes rest_get_server() to retrieve the global WP_REST_Server instance created in the bootstrap process. But, if the instance has not been set up yet, it is instantiated then and the rest_api_init action hook is run. This means that every function added to the rest_api_init hook will fire at that time. This could result in a large performance hit.
For example, say register_rest_route() is called on the init action, or, just called in a theme’s functions.php file. The REST API server would be set up for every WordPress request, even those that are not actually aimed at the REST API.
Missing Endpoints
If register_rest_route() is called too early, it’s also possible that endpoints will go missing and never be registered. This happens when other plugins are not given the chance to register their rest_api_inithooksHooksIn WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same..
For example, say register_rest_route() is called directly in an mu-plugin file. This will cause the REST API to be set up before regular plugins are run, so their rest_api_init hooks will not be registered.
Good and Bad Practices
Let’s look at a few code examples and detail why they are good or bad.
In this example, register_rest_route() is called directly in a file without being attached to an action hook. This means the function will be called as soon as the file is loaded by WordPress. All of the potential issues detailed above are possible, and a _doing_it_wrong() notice will be triggered.
In this example, register_rest_route() is correctly placed inside of a function that is added to the rest_api_init action hook. It will only execute when the rest_api_init action hook is executed. The potential issues detailed above are avoided, and no _doing_it_wrong() notice is triggered.
Changes Required
Plugins and Themes
All plugins and themes should double check that their REST API endpoints are being registered correctly using the rest_api_init action hook. This best practice is also mentioned in the Routes and Endpoints section of the REST API Handbook. If this was a resource used when developing, chances are you won’t have to change anything!
Unit Tests
Because some unit tests require custom endpoints to exist, it is not uncommon for a test method to call register_rest_route() directly. If a test method calls the function before rest_api_init, a previously passing test method may now fail. This can be fixed in two ways.
The first way is to use rest_get_server() to create the WP_Rest_Server instance for your tests. Since rest_api_init is run within that function, this will prevent the notice. This approach can be seen in the Tests_REST_Server class. The wp_rest_server_classfilterFilterFilters 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. still allows you to replace the default WP_Rest_Server class with your own for testing purposes with this method.
The second way is to call do_action( 'rest_api_init' ); directly in your test method or setUp() method. This method is for scenarios where complete control is needed over the REST server setup process. This can approach can be seen in the Tests_REST_API class.
You must be logged in to post a comment.