Removing posts from the returned wp_query. Cannot use object of type WP_Query as array

My end goal is to perform 3 custom field filters on a sets of filters on a WP_Query. The difficulty arises as I need to use both AND/OR relations between the 3 filters:

  • field1 = A AND
  • field2 = null OR field2 = B

The way I’m trying to tackle this is by performing the first field filter within the original WP_Query as this will do the bulk of the filter. Then I want to gather a list of post ID’s that match the (field2 = null OR field2 = B) statement (using a second WP_Query) and then doing a check on the original WP_Query against the list of post_id’s and remove any matches.

the code I’ve got to do that so far is:

foreach($query['posts'] as $thepost) {
        if(in_array($thepost['ID'], $new_query_results['posts'])){
            unset($thepost);
        }
}

With $query being the main WP_Query and $new_query_results being the WP_Query that simply returns an array of post ID’s

Running this code gives me the error:

Fatal error: Cannot use object of type WP_Query as array in functions.php on line 190

Line 190: foreach($query['posts'] as $thepost) {

Firstly, is there a better way to achieve my goal? If not can anyone work out a way to get that code snippet working?

1 Answer
1

WP_Query is an object not an array. Needed to use $query->posts

For anyone interested I found a better way to attack this problem. Performing the second query with the OR statements and outputting to an array of post ID’s allowed me to filter the original query based off that list.

Leave a Comment