Title: 5.1 | Make WordPress Core

---

#  Tag Archives: 5.1

 [  ](https://profiles.wordpress.org/flixos90/) [Felix Arntz](https://profiles.wordpress.org/flixos90/)
6:02 pm _on_ January 28, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/),
[multisite ( 90 )](https://make.wordpress.org/core/tag/multisite/), [networks-sites ( 43 )](https://make.wordpress.org/core/tag/networks-sites/)

# 󠀁[Multisite Support for Site Metadata in 5.1](https://make.wordpress.org/core/2019/01/28/multisite-support-for-site-metadata-in-5-1/)󠁿

WordPress 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** 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 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. 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 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. 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 coreCore Core is the set of software required to run
WordPress. The Core Development Team builds WordPress. which regards the fatal error
protection mechanism (see [#44458](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/37923)
and [#40229](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/40948)
for more information.

_Props [@jeremyfelt](https://profiles.wordpress.org/jeremyfelt/) for review.

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/),
[#multisite](https://make.wordpress.org/core/tag/multisite/), [#networks-sites](https://make.wordpress.org/core/tag/networks-sites/)

 [  ](https://profiles.wordpress.org/peterwilsoncc/) [Peter Wilson](https://profiles.wordpress.org/peterwilsoncc/)
11:28 pm _on_ January 23, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/)

# 󠀁[Cron API changes in WordPress 5.1](https://make.wordpress.org/core/2019/01/23/cron-api-changes-in-wordpress-5-1/)󠁿

WordPress 5.1 sees a number of developer focused changes to the Cron 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.. These
changes were discussed and made in [#21072](https://core.trac.wordpress.org/ticket/21072),
[#32656](https://core.trac.wordpress.org/ticket/32656), [#45797](https://core.trac.wordpress.org/ticket/45797),
and [#45976](https://core.trac.wordpress.org/ticket/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
CoreCore Core 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.

This function does not accept any arguments.

For more information, check out the [source code for this function](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/cron.php?rev=44483#L867).

### `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](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/cron.php?rev=44483#L495).

## 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 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.
follows the pattern of bypassing the Core function if the filterFilter Filters are
one of the two types of Hooks [https://codex.wordpress.org/Plugin_API/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 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/](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:

    ```notranslate
    // 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 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.
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](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/)

 [  ](https://profiles.wordpress.org/desrosj/) [Jonathan Desrosiers](https://profiles.wordpress.org/desrosj/)
7:00 pm _on_ January 23, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/)

# 󠀁[Miscellaneous Developer-Focused Changes in 5.1](https://make.wordpress.org/core/2019/01/23/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:

    ```notranslate
    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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/browser/trunk/wp-tests-config-sample.php)`
[ file](https://core.trac.wordpress.org/browser/trunk/wp-tests-config-sample.php)
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.

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

For more information, see [#39734](https://core.trac.wordpress.org/ticket/39734).

## New 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/](https://wordpress.org/plugins/)󠁿 or can be cost-based plugin from a third-party. Action 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.

In WordPress CoreCore Core 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.**

For more information, see [#41346](https://core.trac.wordpress.org/ticket/41346).

## Short Circuit FilterFilter Filters are one of the two types of Hooks 󠀁[https://codex.wordpress.org/Plugin_API/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](https://core.trac.wordpress.org/ticket/21112#comment:5),
such as always replacing certain terms in post names (changing `wp` to `wordpress`,
for example).

For more information, see [#21112](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/42742)).
 * A [large number of inline documentation updates](https://core.trac.wordpress.org/query?status=closed&focuses=~docs&milestone=5.1&group=component&max=200&col=id&col=summary&col=status&col=milestone&col=owner&col=type&col=priority&order=priority)
   have been made to ensure accuracy proper formatting.

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/)

 [  ](https://profiles.wordpress.org/boonebgorges/) [Boone Gorges](https://profiles.wordpress.org/boonebgorges/)
3:54 pm _on_ January 23, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/),
[query ( 8 )](https://make.wordpress.org/core/tag/query/)   

# 󠀁[LIKE support for meta keys in 5.1](https://make.wordpress.org/core/2019/01/23/like-support-for-meta-keys-in-5-1/)󠁿

WordPress 5.1 introduces limited `LIKE`support for metaMeta Meta is a term that 
refers to the inside workings of a group. For us, this is the team that works on
internal WordPress sites like WordCamp Central and Make WordPress. keys 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](https://core.trac.wordpress.org/ticket/42409) and [[42768]](https://core.trac.wordpress.org/changeset/42768).
Here’s an example of how the new parameter is used:

    ```wp-block-code
    $q = new WP_Query(
      array(
        'post_type'  => 'my_custom_post_type',
        'meta_query' => array(
          array(
            'compare_key' => 'LIKE',
            'key'         => 'foo',
          ),
        ),
      )
    );
    ```

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

This enhancementenhancement Enhancements 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 MySQLMySQL MySQL 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](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_key`feature in WP 5.1 is not a full replacement for
the previous behavior, but it should allow for most use cases. See [#43445](https://core.trac.wordpress.org/ticket/43445)
for discussion.

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/),
[#query](https://make.wordpress.org/core/tag/query/)

 [  ](https://profiles.wordpress.org/boonebgorges/) [Boone Gorges](https://profiles.wordpress.org/boonebgorges/)
1:54 pm _on_ January 23, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/),
[taxonomy ( 16 )](https://make.wordpress.org/core/tag/taxonomy/)   

# 󠀁[Improved taxonomy metabox sanitization in 5.1](https://make.wordpress.org/core/2019/01/23/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 coreCore Core is the set of software required
to run WordPress. The Core Development Team builds WordPress. UIUI User interface
for custom taxonomies.

Custom taxonomies can specify which metaboxMetabox A 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 taxonomyTaxonomy A taxonomy is a way to group things
together. In WordPress, some common taxonomies are category, link, tag, or post 
format. [https://codex.wordpress.org/Taxonomies#Default_Taxonomies](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_cb`
   associated with the taxonomy. This will fix the underlying 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. 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](https://core.trac.wordpress.org/ticket/36514)
and [[42211]](https://core.trac.wordpress.org/changeset/42211).

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/),
[#taxonomy](https://make.wordpress.org/core/tag/taxonomy/)

 [  ](https://profiles.wordpress.org/adamsilverstein/) [Adam Silverstein](https://profiles.wordpress.org/adamsilverstein/)
8:06 pm _on_ January 18, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/)

# 󠀁[New User Related Short Circuit Filters](https://make.wordpress.org/core/2019/01/18/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` filterFilter Filters are one of the two types of Hooks [https://codex.wordpress.org/Plugin_API/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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/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 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/](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.

    ```wp-block-code
    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
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. 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](https://github.com/spacedmonkey/wp-user-query-cache),
which enables user query caching.

### Filtering the `count_users()` Function

In addition, a `pre_count_users` filter was added in [#43693](https://core.trac.wordpress.org/ticket/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:

    ```wp-block-code
    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](https://core.trac.wordpress.org/ticket/45800)).
 * A short circuit for `WP_Site_Query` and `WP_Network_Query` with a plan to add
   a `sites_pre_query` filter ([#45749](https://core.trac.wordpress.org/ticket/45749)).
 * A short circuit for `WP_Term_Query` with a plan to add a `terms_pre_query` filter(
   [#41246](https://core.trac.wordpress.org/ticket/41246))[](https://core.trac.wordpress.org/ticket/45749).

### 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](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/)

 [  ](https://profiles.wordpress.org/adamsilverstein/) [Adam Silverstein](https://profiles.wordpress.org/adamsilverstein/)
8:03 pm _on_ January 15, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/)

# 󠀁[New function: human_readable_duration](https://make.wordpress.org/core/2019/01/15/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](https://core.trac.wordpress.org/ticket/39667) where, in addition
to adding units, aria-labels with plain language descriptions were added to improve
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):

![https://cldup.com/P8-Sq1n6Bv.png](https://lh5.googleusercontent.com/bi8aZyoZpIMzOsUwsYMks4UTKen35agGkGhr9B7OygotGD-
HMxy8NB0cQgifZ-SLycXRAfWw8eg4AjPndC45RzEcJiDMsLABMBcibW4xYv9n_IRK68hXR5W7m2Zr45cWWju_O4Li)

Improved time duration accessibility in the media library using the `human_readable_duration()`
function.

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/)

 [  ](https://profiles.wordpress.org/flixos90/) [Felix Arntz](https://profiles.wordpress.org/flixos90/)
5:57 pm _on_ January 14, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/),
[servehappy ( 31 )](https://make.wordpress.org/core/tag/servehappy/)   

# 󠀁[PHP Site Health Mechanisms in 5.1](https://make.wordpress.org/core/2019/01/14/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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/44458#comment:64).

---

WordPress 5.1 will start showing notices to administrators of sites that run on 
long outdated PHPPHP The web scripting language in which WordPress is primarily 
architected. WordPress requires PHP 7.4 or higher versions. This part of the [Servehappy](https://make.wordpress.org/core/features/servehappy/)
and more globally [Site Health](https://make.wordpress.org/core/2019/01/11/site-health-check-project-review-at-wcus/)
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](https://make.wordpress.org/core/2018/12/08/updating-the-minimum-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 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. endpoint 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/](https://wordpress.org/),
so the version numbers can be modified independently of a WordPress release.

![](https://make.wordpress.org/core/files/2019/01/Servehappy-Notice.png)

Warning about outdated PHP version in WordPress backend

The link from the button points to a new [support page about updating PHP](https://wordpress.org/support/update-php/)
which briefly explains the problem and then dives into how to prepare for an update
and perform it. The link URLURL A 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 translationtranslation The process (or result) of changing text, words,
and display formatting to support another language. Also see [localization](https://make.wordpress.org/core/tag/dev-notes+5-1/?output_format=md#l10n),
[internationalization](https://make.wordpress.org/core/tag/dev-notes+5-1/?output_format=md#i18n).
strings thus being available in GlotPress (see [https://meta.trac.wordpress.org/ticket/4004](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 filterFilter Filters are one of the two types
of Hooks [https://codex.wordpress.org/Plugin_API/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:

![](https://make.wordpress.org/core/files/2019/01/Servehappy-Notice-with-custom-
link.png)

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](https://core.trac.wordpress.org/ticket/41191) and [#45686](https://core.trac.wordpress.org/ticket/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 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/](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 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. 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. as well as the output.

![](https://make.wordpress.org/core/files/2019/01/wsod-protection-frontend-note.
png)

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](https://core.trac.wordpress.org/browser/trunk/src/wp-includes/class-wp-fatal-error-handler.php)`,
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](https://core.trac.wordpress.org/ticket/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](https://core.trac.wordpress.org/ticket/43986).

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/),
[#servehappy](https://make.wordpress.org/core/tag/servehappy/)

 [  ](https://profiles.wordpress.org/afercia/) [Andrea Fercia](https://profiles.wordpress.org/afercia/)
3:36 pm _on_ January 14, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/)

# 󠀁[New Styling for Admin Table Pagination Links in WordPress 5.1](https://make.wordpress.org/core/2019/01/14/new-styling-for-admin-table-pagination-links-in-wordpress-5-1/)󠁿

In WordPress 5.1 the adminadmin (and super admin) table pagination links have had
their CSSCSS Cascading Style Sheets. styling modified.

![](https://make.wordpress.org/core/files/2019/01/new-styling-table-pagination-links.
png)

New styling of admin table pagination links in WordPress 5.1

This [CSS change](https://core.trac.wordpress.org/changeset/43019) improves the 
color contrast ratio for better 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) 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 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/](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 TracTrac An open 
source project by Edgewall Software that serves as a bug tracker and project management
tool for WordPress. ticketticket Created for both bug reports and feature development
on the bug tracker., [#41858](https://core.trac.wordpress.org/ticket/41858)

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/)

 [  ](https://profiles.wordpress.org/desrosj/) [Jonathan Desrosiers](https://profiles.wordpress.org/desrosj/)
6:49 pm _on_ January 11, 2019     
Tags: 5.1, [dev-notes ( 654 )](https://make.wordpress.org/core/tag/dev-notes/),
[rest-api ( 111 )](https://make.wordpress.org/core/tag/rest-api/)   

# 󠀁[New REST API Notice in 5.1](https://make.wordpress.org/core/2019/01/11/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 APIREST API The REST
API is an acronym for the RESTful Application Program Interface (API) that uses 
HTTP requests to GET, PUT, POST and DELETE data. It is how the front end of an application(
think “phone app” or “website”) can communicate with the data store (think “database”
or “file system”) [https://developer.wordpress.org/rest-api/](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 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. matches a WordPress
REST API URLURL A 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_init` 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..

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

    ```wp-block-code
    register_rest_route(
    	'hello-world/v1',
    	'/phrase',
    	array(
    		'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

    ```wp-block-code
    function myplugin_register_endpoints() {
    	register_rest_route(
    		'hello-world/v1',
    		'/phrase',
    		array(
    			'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](https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#creating-endpoints).
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](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/tests/rest-api/rest-server.php?rev=44568#L13)`
[ class](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/tests/rest-api/rest-server.php?rev=44568#L13).
The `wp_rest_server_class` filterFilter Filters are one of the two types of Hooks
[https://codex.wordpress.org/Plugin_API/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 ](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/tests/rest-api.php?rev=44568#L16)`
[Tests_REST_API](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/tests/rest-api.php?rev=44568#L16)`
[ class](https://core.trac.wordpress.org/browser/trunk/tests/phpunit/tests/rest-api.php?rev=44568#L16).

You can read more information about this change [in the ticket on Trac](https://core.trac.wordpress.org/ticket/45265).

[#5-1](https://make.wordpress.org/core/tag/5-1/), [#dev-notes](https://make.wordpress.org/core/tag/dev-notes/),
[#rest-api](https://make.wordpress.org/core/tag/rest-api/)

# Post navigation

[← Older posts](https://make.wordpress.org/core/tag/dev-notes+5-1/page/2/?output_format=md)