Debugging ‘Object of class WP_Query could not be converted to int’ error

I am seeing the PHP notice error;

Notice: Object of class WP_Query could not be converted to int in G:\.....\property-search-form.php on line 350

At that line I have a meta query that create a new WP_Query set of results using the code;

$results = new WP_Query( $args );

if(($results == 0) || ($results == false) || ($results == NULL) || !is_object($results) || !($results->have_posts())) {
    return $results;
    }
else {
    return $results;
    }

I understand that the final $result is a number, when I ran it with 9 matching results and used print_r to display the results it returns 9, so not sure what this error means, and how to resolve it.

1 Answer
1

The issue if that your conditional is trying to convert an Object into things that it cannot be converted to. WP_Query returns a WP_Query Object so when it’s tested against Object == 0 – it tries to convert the object into a number during the comparison but cannot.

You instead need to test against $results->have_posts() or one of it’s properties such as 0 === $results->found_posts

Leave a Comment