[wp-trac] [WordPress Trac] #45343: $query->post is null when WP_Query `fields` parameter is present

WordPress Trac noreply at wordpress.org
Wed Nov 14 08:07:12 UTC 2018


#45343: $query->post is null when WP_Query `fields` parameter is present
--------------------------+-----------------------------
 Reporter:  wujek_bogdan  |      Owner:  (none)
     Type:  defect (bug)  |     Status:  new
 Priority:  normal        |  Milestone:  Awaiting Review
Component:  General       |    Version:
 Severity:  normal        |   Keywords:
  Focuses:                |
--------------------------+-----------------------------
 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
 <?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
 }

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/45343>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list