Query: Improve caching behavior for WP_Query when retrieving id=>parent fields

In [53941], the addition of query caching to `WP_Query` brought about an unintended issue when querying for fields equal to id=>parent. Specifically, on websites with object caching enabled and a substantial number of pages, the second run of this query triggered the `_prime_post_caches` function for id=>parent. This led to the unnecessary priming of post, meta, and term caches, even when only id and parent information were requested.

This commit addresses this issue by introducing a new function, `_prime_post_parents_caches`, which primes a dedicated cache for post parents. This cache is primed during the initial query execution. Subsequently, the `wp_cache_get_multiple` function is employed to retrieve all post parent data in a single object cache request, optimizing performance.

Additionally, this commit extends the coverage of existing unit tests to ensure the reliability of the changes.

Props kevinfodness, joemcgill, peterwilsoncc, LinSoftware, thekt12, spacedmonkey.
Fixes #59188

git-svn-id: https://develop.svn.wordpress.org/trunk@56763 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Jonny Harris
2023-10-03 14:59:22 +00:00
parent 53eff06da7
commit 6ee34689ca
5 changed files with 282 additions and 18 deletions

View File

@@ -7262,6 +7262,7 @@ function clean_post_cache( $post ) {
wp_cache_delete( $post->ID, 'posts' );
wp_cache_delete( $post->ID, 'post_meta' );
wp_cache_delete( $post->ID, 'post_parent' );
clean_object_term_cache( $post->ID, $post->post_type );
@@ -7795,6 +7796,31 @@ function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache
}
}
/**
* Prime post parent caches.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int[] $ids ID list.
*/
function _prime_post_parents_caches( array $ids ) {
global $wpdb;
$non_cached_ids = _get_non_cached_ids( $ids, 'post_parent' );
if ( ! empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.ID, $wpdb->posts.post_parent FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
if ( $fresh_posts ) {
$post_parent_data = array();
foreach ( $fresh_posts as $fresh_post ) {
$post_parent_data[ (int) $fresh_post->ID ] = (int) $fresh_post->post_parent;
}
wp_cache_add_multiple( $post_parent_data, 'post_parent' );
}
}
}
/**
* Adds a suffix if any trashed posts have a given slug.
*