Make WordPress Core

Opened 4 months ago

#60984 new defect (bug)

WP_Query is returning the two same post instead of one

Reported by: tremidkhar's profile tremidkhar Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 6.5
Component: Query Keywords:
Focuses: Cc:

Description

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
/**
 * 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 sticky post is being processed. Thus, the post__in is being applied twice in the query.

Attachments (1)

screenshot.png (425.6 KB) - added by tremidkhar 4 months ago.
Query Loop block rendered two CPT post instead of one

Download all attachments as: .zip

Change History (1)

@tremidkhar
4 months ago

Query Loop block rendered two CPT post instead of one

Note: See TracTickets for help on using tickets.