[wp-trac] [WordPress Trac] #60984: WP_Query is returning the two same post instead of one
WordPress Trac
noreply at wordpress.org
Wed Apr 10 19:36:44 UTC 2024
#60984: WP_Query is returning the two same post instead of one
--------------------------+-----------------------------
Reporter: tremidkhar | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: Awaiting Review
Component: Query | Version: 6.5
Severity: normal | Keywords:
Focuses: |
--------------------------+-----------------------------
WP_Query is returning two same posts when hooked into `pre_get_post` with
a certain condition.
Steps to reproduce the issue
- Add a hook into the `pre_get_post` with a condition for a certain post
type.
- Set the `post__in` query variable to a specific ID of the same post
type.
- Set the `posts_per_page` to 1
I tested this using the `Query Loop` block, and it always rendered two
same posts instead of one.
The query block settings
{{{
<!-- wp:query
{"queryId":148,"query":{"perPage":"1","pages":0,"offset":0,"postType":"quote","order":"desc","orderBy":"date","author":"","search":"","exclude":[],"sticky":"","inherit":false,"parents":[]},"align":"wide"}
-->
}}}
The PHP `pre_get_posts` includes the hotfix for this issue.
{{{#!php
<?php
<?php
/**
* Modifies the query for the Quote of the Day post type.
*
* @param WP_Query $query The WP_Query instance (passed by reference).
*
* @return void
*/
function wporg_modify_quote_of_the_day_query( WP_Query $query ): void {
if ( ! $query->is_home() || 'quote' !== $query->get( 'post_type' )
) {
return;
}
// Prevent infinite loops.
remove_action( 'pre_get_posts', __FUNCTION__ );
$daily_quote = wporg_get_daily_quote(); // Custom function that
return a WP_Post (quote CPT) instance.
$daily_quote_id = $daily_quote instanceof WP_Post ?
$daily_quote->ID : null;
$query->set( 'post__in', array( $daily_quote_id ) );
$query->set( 'posts_per_page', 1 );
// Hotfix: Two quote CPTs are being displayed.
$query->set( 'ignore_sticky_posts', true );
// Re-add the action.
add_action( 'pre_get_posts', __FUNCTION__ );
}
add_action( 'pre_get_posts', 'wporg_modify_quote_of_the_day_query' );
}}}
The issues seem to be in the `class-wp-query.php` file where the
[https://github.com/WordPress/wordpress-
develop/blob/f525e665b6ea6e88289d82cad5fc1dfac57db109/src/wp-includes
/class-wp-query.php#L3499-L3516 sticky post is being processed]. Thus, the
`post__in` is being applied twice in the query.
--
Ticket URL: <https://core.trac.wordpress.org/ticket/60984>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list