‘Trying to get property of non-object’ when using WP_Query with ‘fields’ => ‘ids’

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;

Leave a Comment

tech