Query: Ensure secondary loops populate the full global post.

Modifies `WP_Query::the_post()` to ensure the entire global post object is populated regardless of the `fields` parameter initially set by the developer.

In secondary loops, this ensures that `get_the_content()` and other getter functions operate as documented when called without a post ID and return the appropriate data for the global post object.

This introduces consistency when starting the loop and the `fields` parameter is set to `id=>parent` to the behaviour when set to either `all` or `ids`.

There is no change to the `WP_Query::$posts` parameter nor when a query is made without starting the secondary loop, ie without calling `WP_Query::the_post()`.

Props juzar, mukesh27, oglekler, peterwilsoncc, sirlouen, joemcgill.
Fixes #56992.


Built from https://develop.svn.wordpress.org/trunk@59919


git-svn-id: http://core.svn.wordpress.org/trunk@59261 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Peter Wilson 2025-03-03 21:45:21 +00:00
parent 122e00bdb8
commit d57ecb8b98
2 changed files with 30 additions and 6 deletions

View File

@ -3738,14 +3738,28 @@ class WP_Query {
global $post;
if ( ! $this->in_the_loop ) {
// Only prime the post cache for queries limited to the ID field.
$post_ids = array_filter( $this->posts, 'is_numeric' );
// Exclude any falsey values, such as 0.
$post_ids = array_filter( $post_ids );
// Get post IDs to prime incomplete post objects.
$post_ids = array_reduce(
$this->posts,
function ( $carry, $post ) {
if ( is_numeric( $post ) && $post > 0 ) {
// Query for post ID.
$carry[] = $post;
}
if ( is_object( $post ) && isset( $post->ID ) ) {
// Query for object, either WP_Post or stdClass.
$carry[] = $post->ID;
}
return $carry;
},
array()
);
if ( $post_ids ) {
_prime_post_caches( $post_ids, $this->query_vars['update_post_term_cache'], $this->query_vars['update_post_meta_cache'] );
}
$post_objects = array_map( 'get_post', $this->posts );
$post_objects = array_map( 'get_post', $post_ids );
update_post_author_caches( $post_objects );
}
@ -3764,6 +3778,16 @@ class WP_Query {
}
$post = $this->next_post();
// Get the post ID.
if ( is_object( $post ) ) {
$global_post_id = $post->ID;
} else {
$global_post_id = $post;
}
// Ensure the global $post is the full post object.
$post = get_post( $global_post_id );
$this->setup_postdata( $post );
}

View File

@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '6.8-alpha-59918';
$wp_version = '6.8-alpha-59919';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.