Make WordPress Core

Opened 7 years ago

Last modified 4 weeks ago

#45343 new defect (bug)

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

Reported by: wujek_bogdan's profile wujek_bogdan Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Query Keywords: dev-feedback needs-testing close
Focuses: Cc:

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 (2)

45343.patch (755 bytes) - added by mukesh27 7 years ago.
Patch
45343.diff (721 bytes) - added by callumbw95 4 weeks ago.
Modernised patch as the previous patch wasn't working in the latest version of WordPress

Download all attachments as: .zip

Change History (7)

#1 @mukesh27
7 years ago

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

#2 @mukesh27
7 years 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
7 years ago

Patch

#3 @mukesh27
7 years ago

  • Keywords needs-testing added; needs-patch removed

@callumbw95
4 weeks ago

Modernised patch as the previous patch wasn't working in the latest version of WordPress

#4 @callumbw95
4 weeks ago

Hi all,
I know this is an older issue now but as its still occurring in the latest release and on trunk I thought I would throw my hat in to the ring to get this resolved. I have taken a look at the previous patch, and this didn't appear to work in the current version. Because of this I have updated the patch and tested this and all appears to be working now. Hopefully this can help unstick this ticket.

#5 @callumbw95
4 weeks ago

  • Keywords close added

Hi again, I should have done a bit more digging before submitting my patch, as it seems between this ticket initially being raised and now the $query->post variable is now documented as being set to null when passing 'ids' or 'id=>parent' to the fields argument. As of such this ticket most likely should be closed as it is no longer relevant in the latest version of WordPress.

Note: See TracTickets for help on using tickets.