Object type specific registration hooks in 6.0

If you’ve ever worked with post types in WordPress, chances are you’ve used register_post_type_args filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. where you had to perform post type check. In WordPress 6.0 you won’t have to do that any more as new object type 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. are introduced.

Similar to other dynamic hooks, these will allow you to directly hook into your custom post types and custom taxonomies.

New filters:

  • register_{$post_type}_post_type_args – Filters the arguments for registering a specific post type.
  • register_{$taxonomy}_taxonomy_args – Filters the arguments for registering a specific 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..

New actions:

  • registered_post_type_{$post_type} – Fires after a specific post type is registered.
  • registered_taxonomy_{$taxonomy} – Fires after a specific taxonomy is registered.

For more info see #53212.

#6-0, #dev-notes, #dev-notes-6-0

Media: storing file size as part of metadata

In #49412 a tweak was made to the upload process. When files are uploaded to the WordPress media library, the file’s size is now stored as part of the metadata. This means that when calling the wp_get_attachment_metadata function, developers will easily be able to receive the file size of a selected image without having to call the php function filesize. This change is especially useful in situations when media is being offloaded to a third party, such as cloud services like Amazon’s S3 and Google cloud storage or a networknetwork (versus site, blog) share like NFS; as a call to get the file’s size can result in slow calls to an external server. 

Along with saving the file size to the attachment’s metadata, a new function and filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. have been added. The new wp_filesize function is useful when storing attachments on a third party source. It means that value can be filtered, preventing a possibility of a slow call to an external server. 

It is recommended that authors and maintainers of plugins designed to offload attachments to external services review this change and check that it does not affect your pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party.

Props to @milana_cap for review and proofreading.

#6-0, #dev-notes, #dev-notes-6-0, #media

Performance increase for sites with large user counts (now also available on single site)

In WordPress 6.0, websites with more than 10,000 users will see improvements in handling users. Prior to changes in #38741, sites with more than 10,000 users would suffer from slow page loading time in the user and post list screens. 

The user screen was slow because a complex SQL query was run to get the number of users for each role. This sometimes resulted in page timeout or failures to load. On the post edit screen, a dropdown of authors in the quick edit option used to change the post’s author. On large sites, this results in thousands of options rendered on the page, which creates a large amount of markup and causes timeouts and slowdowns. 

Introducing large sites

The idea of a large networknetwork (versus site, blog) in 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 configurations of WordPress has existed since WordPress 3.0. A network is considered large when it has over 10,000 users. When marked as such, any real time calculation of the number of users is skipped and all counts of users are deferred to scheduled (cron) events. 

This idea of a large network has now been ported to single site installs of WordPress. Any site with more than 10,000 users is marked as large. Once this threshold is met, real time counts, such as ones noted above, no longer occur on every page load. This means that when viewing user lists, the count next to each user role will be missing. This massively improves the performance of the page page load and prevents slow database queries causing PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher timeout errors, which in turn helps ensure the user list renders every time on large sites. 

This change includes some new functions:

  • get_user_count
    Now available for both single- and multi-site installations. For sites with over 10,000 users recounting is performed twice a day by a scheduled event. 
  • wp_update_user_counts
    Perform a user count and cache the result in the user_count site option. 
  • wp_is_large_user_count
    Determines whether the site has a large number of users. The default threshold of 10,000 users can be modified using a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. of the same name.

Now that the get_user_count is available for both single and multisite, it is strongly recommended not to use the count_users function in your code. This function is not performant and is the root cause of issues noted above. Wherever possible, every instance of count_users in coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. has been converted to use get_user_count, which is also recommended action for pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party authors. 

Props to @kkautzman, @milana_cap, and @bph for review and proofreading.

#6-0, #dev-notes, #dev-notes-6-0, #performance

WP_User_Query now accepts fields options in WordPress 6.0 

Prior to the WordPress 6.0 release the function WP_User_Query would only accept ID and all_with_meta/all in the fields parameter.

The change

You can now pass any of these options in the field parameter and get the associated values back

  • ‘ID’
  • ‘display_name’
  • ‘user_login’
  • ‘user_pass’
  • ‘user_nicename’
  • ‘user_email’
  • ‘user_url’
  • ‘user_registered’
  • ‘user_activation_key”
  • ‘user_status’

    and for a multi site also
  • ‘spam’
  • ‘deleted’

The following return WP_user objects in an array

  • ‘all’ – default,
  • ‘all_with_meta’

Example

Code like this:

$users = get_users( ['fields' => 'display_name'] );

Will now return values like this

Array ( 
  [0] => Jack 
  [1] => jb 
  [2] => momo 
  [3] => Roberta
)

Props to @peterwilsoncc, @kkautzman, and @milana_cap for review and proofreading.

#6-0, #dev-notes, #dev-notes-6-0

Caching improvements in WordPress 6.0

As part of the release of WordPress 6.0, the new Performance team has been working on several improvements to the coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.. There are a few new additions to the WordPress Caching 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..

Batch API methods for Cache Operations (wp_cache_*_multiple)

The function wp_cache_get_multiple() was added in WordPress 5.5. This allowed for multiple cache keys to be collected in just one request. To complete this API, a full CRUDCRUD Create, read, update and delete, the four basic functions of storing data. (More on Wikipedia.) was needed and has been added via the following functions:

  • wp_cache_add_multiple
  • wp_cache_set_multiple
  • wp_cache_delete_multiple

All of these functions accept an array of data to be passed so that multiple cache objects can be created, edited, or deleted in a single cache call.

In WordPress core, these are just wrappers for core functions to allow multiple keys to be passed in one function call, but this would also allow object caching drop-in developers to implement them if their back-end supports it.

Example usage of wp_cache_add_multiple( $data, $group = '', $expire = 0 )

  • $data: Array of key and value pairs to be added.
  • $group: Optional. String. Where the cache contents are grouped. Default ”.
  • $expire: Optional. Int. When to expire the cache in seconds. Default 0 (no expiration).
wp_cache_add_multiple( array( 'foo1' => 'value1', 'foo2' => 'value2' ), 'group1' );

Example usage of wp_cache_delete_multiple( $data, $group = '' )

  • $data: Array of keys to be deleted.
  • $group: Optional. String. Where the cache contents are grouped. Default ”.
wp_cache_delete_multiple( array( 'foo1', 'foo2' ), 'group1' );

Example usage of wp_cache_set_multiple( $data, $group = '', $expire = 0 )

  • $data: Array of key and value pairs to be set.
  • $group: Optional. String. Where the cache contents are grouped. Default ”.
  • $expire: Optional. Int. When to expire the cache in seconds. Default 0 (no expiration).
wp_cache_set_multiple( array( 'foo1' => 'value1', 'foo2' => 'value2' ), 'group1' );

With these additions, some additional core refactoring has been done to utilize these new functions. See more details in TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. #55029.

Allow runtime cache to be flushed (wp_cache_flush_runtime)

As discussed in the Performance issue #81 and Trac #55080, Core needed a way to allow users to flush the runtime (in-memory) cache without flushing the entire persistent cache.

This feature was often requested for instances where long-running processes such as Action Scheduler or WP-CLIWP-CLI WP-CLI is the Command Line Interface for WordPress, used to do administrative and development tasks in a programmatic way. The project page is http://wp-cli.org/ https://make.wordpress.org/cli/ are run.

Example usage of  wp_cache_flush_runtime()

$counter = 0;
foreach ( $posts as $post ) {
	wp_insert_post( $post );
	if ( 100 === $counter ) {
		wp_cache_flush_runtime();
		$counter = 0;
	} 
	$counter++;
}

The above example would reset the runtime cache after 100 posts are inserted into the database.

Thanks to @mxbclang, @milana_cap, @costdev, @webcommsat, and @spacedmonkey for peer review.

#6-0, #cache, #dev-notes, #dev-notes-6-0, #performance

Taxonomy performance improvements in WordPress 6.0

As part of the 6.0 release of WordPress, the new performance team has been hard at work to improve the performance of term queries. There are many term queries on the average page load and improving these improves the performance of WordPress in general. 

Improvement to term query caching. 

Queries run by WP_Term_Query have been cached since 4.6. The way these caches are primed and handled has been improved in WordPress 6.0.

Removing to cache limit

Prior to WordPress 6.0, term query caches were limited to a 24-hour period for those using persistent object caching. This limitation is now removed, so if caches are not invalidated, it means that term query should cache much longer. For inactive sites or overnight, caches should remain primed, which should improve site performance. 

For more information, see #54511.

Term query cache only caches the term ID

Term query caches have been changed so that instead of caching the whole term object, now only the term IDs are cached. This means that the value stored in cache will be much smaller (in terms of memory) and will not fill up memory in session or persistent object cache.

Once all the IDs for the terms are loaded, the _prime_term_cache function is called. This loads into memory terms that are not already in cache. If the term is already in memory, then it is not loaded again, which is a performance benefit. On an average page load, a term may be requested multiple times, like the case of a tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) archive page. Early in the page load, get_term_by, will prime the term cache and all other calls, such as get_the_terms, will have the term already primed in page memory. This results, in most cases in fewer and smaller queries that are run against the term table. 

For more information, see #37189.

Improved term query cache key generation

Previously, similar term queries that have similar cache keys would result in basically the same query being run twice on a single page load. Because all queries now only get the term ID and store it in cache (see above), the cache exactly the same. For example, you create a call to get_terms where you request all categories and return only the field slug. If you do the same query and request only the name, then this would hit the same cache.

Another improvement is the handling of parameters that can be passed to WP_Term_Query that can be ambiguous. Fields like slug that can be either a string or an array are now converted to always be an array, meaning that the likelihood of reusing a cache is higher as the cache key is the same, no matter which type of parameter is passed. 

For more information, see #55352.

Improve performance for navigation menuNavigation Menu A theme feature introduced with Version 3.0. WordPress includes an easy to use mechanism for giving various control options to get users to click from one place to another on a site. items

Convert wp_get_nav_menu_items to use a 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. query

This replaces usage of get_objects_in_term function with a simple taxonomy query. This replacement converts the use of two queries to get the menu items to use one simple query. This saves one query for each menu requested and adds consistency. 

For more information, see #55372.

Prime all term and posts caches in wp_get_nav_menu_items

The wp_get_nav_menu_items function now calls _prime_term_cache and _prime_post_cache for all objects linked to menu items. If a menu contains a list of categories and pages, all the related objects are now primed in two cache calls (one for terms and one for posts). This will result in far fewer requests to the database and cache.

For more information, see #55428.

Convert term_exists to use get_terms

The function term_exists has now been converted to use get_terms ( WP_Term_Query ) internally replacing raw uncached database queries. This function was one of the last places to perform raw queries to the terms table in the database. Using the get_terms function has a number of key benefits, including: 

  • Consistency with other coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. functions like get_term_by
  • The ability to filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. the results.
  • Results of get_terms are cached 

term_exists is designed for back-end use and is mostly used in core functions designed to write data to the term table. However, term_exists can and is used by some theme and pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party developers. This results in raw uncachable and unfilterable queries to be run on the front-end of a site. 

Now that term_exists is cached, custom import / migrationMigration Moving the code, database and media files for a website site from one server to another. Most typically done when changing hosting companies. tools may need to check if they correctly cache invalidation terms. If your importation code is using core functions like wp_insert_term, then there is no need to do anything, as core does its own cache invalidation for you. However, if you are writing data to the term table manually, then you may need to call the clean_term_cache function. 

For those that need to ensure that term_exists is getting an uncached result, there are two ways to do this:

  1. Using the new term_exists_default_query_args filter 
$callback = function ( $args ) {
   $args['cache_domain'] = microtime();
};
add_filter( 'term_exists_default_query_args',  $callback );
$check = term_exists( 123, 'category' );
remove_filter( 'term_exists_default_query_args',  $callback );
  1. Using wp_suspend_cache_invalidation
wp_suspend_cache_invalidation( true );
$check = term_exists( 123, 'category' );
wp_suspend_cache_invalidation( false );

For more information, see #36949.

Add a limit to taxonomy queries

The ​​WP_Tax_Query class is used in WP_Query to limit queries by term. Under the hood, ​​WP_Tax_Query uses ​​WP_Term_Query, which means that ​​WP_Tax_Query will get the benefits of the cache improvements documented above. The ​​WP_Tax_Query run, which transforms term slugs / names into term IDs to be queried, now has a limit added to it. This query limit improves the performance of the query, as well as improves the likelihood of an existing cache query to continue to exist in the object cache. For example, a standard tag archive calls get_term_by and primes the cache. By the time it gets to the ​​WP_Tax_Query, that query is being loaded from cache. This removes one query per tag archive page. 

For more information, see #55360.

Props to @milana_cap, @mxbclang, @flixos90 for peer review.

#6-0, #dev-notes, #dev-notes-6-0, #performance, #users

Changes to do_parse_request filter in WordPress 6.0

Prior to the WordPress 6.0 release pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and theme developers used the do_parse_request filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. to hot-wire requests and hook in early to render custom pages. Not needed post queries and 404 lookups were still run. This resulted in unnecessary SQL queries running on these requests.

The change

In 6.0 we added a return value to the parse_request method of the WP class. These queries are not needed and now skipped if false is returned by the do_parse_request filter.

We encourage developers to update their code run by the filter  do_parse_request to return false if they are handling the request in their code.

Example

In the simplest filter:

add_filter( 'do_parse_request', '__return_false' );

But you might want to check for a parameter before returning:

function wporg_add_custom_query( $do_parse, $wp, $extra_query_vars ) {
    if ( 'CUSTOM_VALUE' === $extra_query_vars['custom_arg'] ) {
        return false;
    }

    return $do_parse;
}

add_filter( 'do_parse_request', 'wporg_add_custom_query', 10, 3 );

Props to @sergey, @kkautzman, and @milana_cap for review and proofreading.

#6-0, #dev-notes, #dev-notes-6-0, #performance

New filter to modify content images in WordPress 6.0

WordPress 6.0 introduces a new filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output.  wp_content_img_tag to allow adjustment of images in a blob of HTMLHTML HyperText Markup Language. The semantic scripting language primarily used for outputting content in web browsers. content, most prominently post content via the_content filter.

WordPress 5.5 originally introduced the wp_filter_content_tags() function to modify certain elements, primarily images, in a blob of HTML content. Prior to the WordPress 6.0 release, it was not possible to alter these image tags without duplicating the complex regex logic in the wp_filter_content_tags() function. This increased complexity and overhead. The new wp_content_img_tag filter solves this problem.

How to use the filter

The new wp_content_img_tag filter passes the following parameters:

  • string $filtered_image: The full img tagtag A directory in Subversion. WordPress uses tags to store a single snapshot of a version (3.6, 3.6.1, etc.), the common convention of tags in version control systems. (Not to be confused with post tags.) with attributes that will replace the source image tag.
  • string $context: Additional context, like the current filter name or the function name from where this was called.
  • int $attachment_id: The image attachment ID. May be 0 in case the image is not an attachment.

The filter must return a string which will then replace the img tag passed to the filter.

Example

Here is an example in which the new filter is used to add a border-color style attribute to every image tag in the content.

function myplugin_img_tag_add_border_color( $filtered_image, $context, $attachment_id ) {
	$style = 'border-color: #cccccc;';

	$filtered_image = str_replace( '<img ', '<img style="' . $style . '" ', $filtered_image );

	return $filtered_image;
}
add_filter( 'wp_content_img_tag', 'myplugin_img_tag_add_border_color', 10, 3 );

The wp_filter_content_tags() function was originally introduced to facilitate lazy-loading support for images and has since become the standard approach for modifying in-content images for various performance enhancements. The new wp_content_img_tag filter expands these capabilities by giving control to pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party developers to add their own customizations.

For more context on the new filter, implementation see #55347.

Props to @flixos90 , @kkautzman, and @milana_cap for review and proofreading.

#6-0, #dev-notes, #dev-notes-6-0, #performance

WordPress 6.0 Accessibility Improvements

Thank you to @joedolson and @alexstine for collaborating on this post. 

Improving 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) requires ongoing effort and this post seeks to highlight some of the ways in which the project has taken action in this area of work for WordPress 6.0, set to release May 24th, 2022. If you’re interested in helping with this work, please join the #accessibility channel in Make SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. and check out how you can get involved. There’s plenty of important work to be done including testing, giving accessibility feedback, and creating PRs to address feedback. 

General improvements

Some improvements didn’t fit nicely into a specific area and instead impacted the general experience of using WordPress. This includes everything from adding button text labels to the site editor to displaying the blockBlock Block is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage using the WordPress editor. The idea combines concepts of what in the past may have achieved with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience. title when removing a block:

Navigation block

While the first version of the navigation block that landed in 5.9 ensured many key accessibility features from the start, more work has been done to refine the experience and to ensure changes to the UIUI User interface continue to include accessibility features: 

Block improvements

Beyond the navigation block, various additional blocks received updates to improve their respective accessibility, wherever they are used: 

List View

List View continues to be an important tool, especially in a full site editing world, allowing folks to quickly navigate between complex content. In this release, tons of work was done to allow it to be more high impact for more people:

Media 

Expect various aspects of managing media to have updates from adding a “Copy URLURL A specific web address of a website or web page on the Internet, such as a website’s URL www.wordpress.org to clipboard” option to make it simpler to get the URL you need to ensuring the full permalink for an image is visible when on mobile devices. 

Quick/Bulk Edit

Quick/Bulk editing has a few improvements that significantly improve keyboard and screen reader operability:

Login and Registration

The login and registration fields now properly set valid autocomplete attributes with a fix to the generate password button that was misleading: 

Themes

A few fixes are in place for various default themes and the overall process of hovering over theme details now has more consistency: 

#6-0, #accessibility, #dev-notes

#dev-notes-6-0