Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

In an attempt to speed up my query, I'm using the following arguments:

$args = array(
    'post_type' => 'product',
    'fields' => 'ids',
);

$query = new WP_Query($args);

While this does return an array of IDs as expected, I keep getting multiple Trying to get property of non-object in /wp-includes/query.php notices. This happens even when I have nothing inside my while other than the_post():

if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
endwhile;
endif;

Is the_post() causing this? Any idea why I'm getting these notices?

share|improve this question
    
What's the fields entry? Never heard of that before. Does it work when you remove that? –  geomagas Mar 10 at 19:21
    
The fields => ids option returns an array of post ids rather than post objects, which (apparently) makes the query faster. –  Dre Mar 10 at 19:28
    
I see. That explains Milo's answer then (apparently)... –  geomagas Mar 10 at 19:30

1 Answer 1

up vote 1 down vote accepted

the_post places the next post object from $query->posts in the global $post and calls setup_postdata, which assumes $post is a post object, as it tries to access member vars of that object, which is where the errors come from.

In this case $posts is just an array of IDs instead of post objects. If you want to iterate over the results, you can do a foreach on $posts:

$args = array(
    'post_type' => 'product',
    'fields' => 'ids',
);
$query = new WP_Query($args);

if ($query->have_posts()):
    foreach( $query->posts as $id ):
        echo 'ID: ' . $id;
    endforeach;
endif;
share|improve this answer
    
Spot on. The documentation for the_post() that I found didn't cover what it actually did in great detail, so I didn't realise it was attempting to access other vars. –  Dre Mar 10 at 19:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.