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
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); endwhile; endif;
the_post() causing this? Any idea why I’m getting these notices?
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
$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;