Multisite Support for Site Metadata in 5.1

WordPress multisite introduces a new database table to store metadata associated with sites. This allows for the storage of arbitrary site data relevant in a multisite / network 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 meta 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 API 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 core which regards the fatal error protection mechanism (see #44458).

This is how the API can be used:

  • get_site_meta( $id, $meta_key, $single )
  • update_site_meta( $id, $meta_key, $meta_value, $prev_value )
  • add_site_meta( $id, $meta_key, $meta_value, $unique )
  • delete_site_meta( $id, $meta_key, $meta_value )

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.

Props @jeremyfelt for review.

#5-1, #dev-notes, #multisite, #networks-sites

Cron API changes in WordPress 5.1

WordPress 5.1 sees a number of developer focused changes to the Cron API. 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 Core 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.

This function does not accept any arguments.

For more information, check out the source code for this function.

wp_get_scheduled_event(): retrieve a scheduled event.

Returns the full event object for a scheduled event.

The new function accepts three arguments:

  • $hook (string) Required, the action hook of the event.
  • $args (array) Optional. An array containing each separate argument to pass to the hook’s callback function.
  • $timestamp (integer or null) Optional. Unix timestamp (UTC) of the event. If not specified, the next scheduled event is returned.

The return value will be either the event object or false if the specified event has not been registered.

For more information, check out the source code for this function.

New filters for modifying cron storage

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 hooks follows the pattern of bypassing the Core function if the filter 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 plugin 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 Beta 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.

#5-1, #dev-notes

Miscellaneous Developer Focused Changes in 5.1

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:

define( 'WP_DEBUG_LOG', '/srv/path/to/custom/log/location/errors.log' );

Here are a few things to keep in mind:

  • The directory must already exist and be writable by the web server’s user.
  • The file does not need to exist. It will be created once the first error occurs as long as the previous condition is met.

Reminder: Any values set to WP_DEBUG_LOG and WP_DEBUG_DISPLAY will be ignored unless WP_DEBUG is set to true.

For more information, see #18391.

Test Suite: New Test Config File Constant

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.

<phpunit ...
		<const name="WP_TESTS_CONFIG_FILE_PATH" value="/path/to/wp-tests-config.php" />

For more information, see #39734.

New Plugin Action Hooks

In WordPress Core today, the plugins_loaded, network_plugins_loaded, and mu_plugins_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.

For more information, see #41346.

Short Circuit Filter 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).

For more information, see #21112.

Additional Developer Goodies

  • 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).
  • A large number of inline documentation updates have been made to ensure accuracy proper formatting.

#5-1, #dev-notes

LIKE support for meta keys in 5.1

WordPress 5.1 introduces limited LIKEsupport for meta 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:

$q = new WP_Query(
    'post_type'  => 'my_custom_post_type',
    'meta_query' => array(
        'compare_key' => 'LIKE',
        'key'         => 'foo',

This will generate a query of the form ... AND meta_key LIKE '%foo%' ....

This enhancement follows from changes in WordPress 4.8.3 to the way that MySQL 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.

#5-1, #dev-notes, #query

Improved taxonomy metabox sanitization in 5.1

WordPress 5.1 will feature a new parameter for register_taxonomy(), 'meta_box_sanitize_cb', which increases flexibility when using core UI for custom taxonomies.

Custom taxonomies can specify which metabox 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 taxonomy 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 bug 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.

For more information, see #36514 and [42211].

#5-1, #dev-notes, #taxonomy

New User Related Short Circuit Filters

WordPress 5.1 introduces new short circuit filters to WP_User_Query and count_users().

The users_pre_query filter 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 plugin can use the filter to replace the default behavior of WP_User_Query with a call to a remote data store.

function myplugin_do_external_users_query( $users, $user_query ) {
	$response = wp_remote_get( 'https://my-remote-data-store/foo/bar' );

	if ( 200 === wp_remote_response_code( $response ) ) {
		$response           = json_decode( wp_remote_retrieve_body( $response ) );
		$users              = array_map( 'intval', $response->user_ids );
		$query->found_users = (int) $response->found_users;

	return $users;
add_filter( 'users_pre_query', 'myplugin_do_external_users_query', 10, 2 );

Similar to posts_pre_query, callbacks must be careful about fields – the external API 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:

function myplugin_do_external_users_count( $user_count) {
	$response = wp_remote_get( 'https://my-remote-data-store/foo/bar' );

	if ( 200 === wp_remote_response_code( $response ) ) {
		$response = json_decode( wp_remote_retrieve_body( $response ) );
		$user_count    = $response->user_count;

	return $user_count;
add_filter( 'pre_count_users', 'myplugin_do_external_users_count', 10, 2 );

More Filters Coming Soon…

Several additional filters for similar query objects are currently being explored and worked on, and are currently slated for a future release:

  • A short circuit for WP_Comment_Query (#45800).
  • 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.

#5-1, #dev-notes

New function: human_readable_duration

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 accessibility:
Improved time duration accessibility in the media library using the human_readable_duration() function.

#5-1, #dev-notes

PHP Site Health Mechanisms in 5.1

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 PHP 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 API endpoint on, so the version numbers can be modified independently of a WordPress release.

Warning about outdated PHP version in WordPress backend

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 URL 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 translation strings thus being available in GlotPress (see Furthermore, the link can be adjusted via either an environment variable WP_UPDATE_PHP_URL intended for hosting providers or a filter 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:

Warning about outdated PHP version with custom URL and related annotation

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 plugin 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 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 HTTP header as well as the output.

Default output in the frontend when WSOD protection detects has detected an error

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.

#5-1, #dev-notes, #servehappy

New Styling for Admin Table Pagination Links in WordPress 5.1

In WordPress 5.1 the admin table pagination links have had their CSS styling modified.

New styling of admin table pagination links in WordPress 5.1

This CSS change improves the color contrast ratio for better 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 plugin and theme developers should verify that this change does not affect them.

You can read more information about this change in the related Trac ticket, #41858

#5-1, #dev-notes

New REST API Notice in 5.1

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 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 API matches a WordPress REST API URL. 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.


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_init hooks.

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.

Bad Practice

		'method'   => 'GET',
		'callback' => 'myplugin_get_endpoint_phrase',

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.

Good Practice

function myplugin_register_endpoints() {
			'method'   => 'GET',
			'callback' => 'myplugin_get_endpoint_phrase',
add_action( 'rest_api_init', `myplugin_register_endpoints` );

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_class filter 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 can read more information about this change in the ticket on Trac.

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