WordPress.org

Make WordPress Core

Opened 11 months ago

Last modified 11 months ago

#45343 new defect (bug)

$query->post is null when WP_Query `fields` parameter is present

Reported by: wujek_bogdan Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords: dev-feedback needs-testing
Focuses: Cc:
PR Number:

Description

Normally, WP_Query returns an object where $query->posts contains an array of posts and $query->post contains the first post. But if the fields parameter is present then $query->post returns null. Is it a bug or an expected behaviour? If it's expected then it should be documented because it's confusing and unintuitive.

Example:

<?php

// Works as expected
$query = new \WP_Query([
    'post_type' => 'my-post-type',
]);

if ($query->have_posts()) {
    $firstPost = $query->post; // returns the same as $query->$posts[0]
}

// Weird behaviour
$query = new \WP_Query([
    'post_type' => 'my-post-type',
    'fields'    => 'ids',
]);

if ($query->have_posts()) {
    $firstPost = $query->post; // returns null
}

Attachments (1)

45343.patch (755 bytes) - added by mukesh27 11 months ago.
Patch

Download all attachments as: .zip

Change History (4)

#1 @mukesh27
11 months ago

  • Component changed from General to Query
  • Keywords needs-patch added

#2 @mukesh27
11 months ago

  • Keywords dev-feedback added

@wujek_bogdan i have checked above issue and found that it's bug in core software. When any WP_Query use fields argument with ids or id=>parent option then system does not set it post variable for that query result and system show null value in result.

@mukesh27
11 months ago

Patch

#3 @mukesh27
11 months ago

  • Keywords needs-testing added; needs-patch removed
Note: See TracTickets for help on using tickets.