Make WordPress Core


Ignore:
Timestamp:
09/21/2023 07:32:55 PM (18 months ago)
Author:
spacedmonkey
Message:

Query: Improved handling of filtered queries in WP_Query.

The WP_Query class enables developers to customize queries using filters like posts_fields_request, posts_request, and the_posts, which can modify both the queried fields and retrieved post objects. In some cases with these filters, incomplete or invalid post objects lacking essential data may arise. To address this, if any of these filters are active during a query, the get_posts method now avoids caching post objects with the usual update_post_caches function call, opting for a call to _prime_post_caches instead. This may occasionally trigger new database queries to prime the post data cache. While this enhancement may result in rare additional database queries, it ensures that invalid post objects aren't cached, prioritizing data consistency and integrity in filtered query scenarios.

Props saulirajala, spacedmonkey, flixos90, mukesh27, peterwilsoncc.
Fixes #58599.

File:
1 edited

Legend:

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

    r56549 r56656  
    32713271        }
    32723272
     3273        $is_unfiltered_query = $old_request == $this->request && "{$wpdb->posts}.*" === $fields;
     3274
    32733275        if ( null === $this->posts ) {
    32743276            $split_the_query = (
    3275                 $old_request == $this->request
    3276                 && "{$wpdb->posts}.*" === $fields
     3277                $is_unfiltered_query
    32773278                && (
    32783279                    wp_using_ext_object_cache()
     
    33373338            $this->posts = array_map( 'get_post', $this->posts );
    33383339        }
     3340
     3341        $unfiltered_posts = $this->posts;
    33393342
    33403343        if ( $q['cache_results'] && $id_query_is_cacheable && ! $cache_found ) {
     
    35303533
    35313534            if ( $q['cache_results'] ) {
    3532                 update_post_caches( $this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
     3535                if ( $is_unfiltered_query && $unfiltered_posts === $this->posts ) {
     3536                    update_post_caches( $this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
     3537                } else {
     3538                    $post_ids = wp_list_pluck( $this->posts, 'ID' );
     3539                    _prime_post_caches( $post_ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
     3540                }
    35333541            }
    35343542
Note: See TracChangeset for help on using the changeset viewer.