Make WordPress Core


Ignore:
Timestamp:
10/03/2023 02:59:22 PM (10 months ago)
Author:
spacedmonkey
Message:

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

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/post.php

    r56711 r56763  
    72637263    wp_cache_delete( $post->ID, 'posts' );
    72647264    wp_cache_delete( $post->ID, 'post_meta' );
     7265    wp_cache_delete( $post->ID, 'post_parent' );
    72657266
    72667267    clean_object_term_cache( $post->ID, $post->post_type );
     
    77977798
    77987799/**
     7800 * Prime post parent caches.
     7801 *
     7802 * @global wpdb $wpdb WordPress database abstraction object.
     7803 *
     7804 * @param int[] $ids ID list.
     7805 */
     7806function _prime_post_parents_caches( array $ids ) {
     7807    global $wpdb;
     7808
     7809    $non_cached_ids = _get_non_cached_ids( $ids, 'post_parent' );
     7810    if ( ! empty( $non_cached_ids ) ) {
     7811        $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 ) ) );
     7812
     7813        if ( $fresh_posts ) {
     7814            $post_parent_data = array();
     7815            foreach ( $fresh_posts as $fresh_post ) {
     7816                $post_parent_data[ (int) $fresh_post->ID ] = (int) $fresh_post->post_parent;
     7817            }
     7818
     7819            wp_cache_add_multiple( $post_parent_data, 'post_parent' );
     7820        }
     7821    }
     7822}
     7823
     7824/**
    77997825 * Adds a suffix if any trashed posts have a given slug.
    78007826 *
Note: See TracChangeset for help on using the changeset viewer.