WordPress nested meta_query using multiple relation OR & AND

WP_Meta_Query is a class defined in wp-includes/meta.php that generates the necessary SQL for meta-related queries. It greatly improved the possibility to query posts by custom fields. In the WP core, it’s used in the WP_Query and WP_User_Query classes.

meta_query is used by WP_Query while we have a situation like we have to search for something that is not native by wordpress and was added by custom code known as custom field.

So, when we have a simple search that contains only one meta key to search through the thing is quite easy like below,

After that we got a condition that we have to search through different meta keys having one single value, there comes the role of “meta_query”. For that we have a code as follows,

Finally we got a situation where we have multiple meta_key with more than one conditions. Suppose I am searching a lawyer with his Area of Law and location, and also location is divided in to three parts i.e. city, state and zip. Here I have to select one of the three meta keys like “city”, “state” & “zip” and also I have to compare it with “Area of Law”. Here is the situation where native functionality of WordPress fails to integrate the functionality. So by googling so much I found the following solution that uses both relation keys i.e. OR & AND in single meta_query. Here is the example,

While some say it works and some denies, in my case this query failed completely. In my case I used an array of keys for “key” and compared it with a sting value inserted for the “value”. But whatever I did, totally violets the rule for meta_query as type of key should be a string while I am putting an array. It only gave me a warning that invalid argument for “trim()” as I was providing an array instead of string. Otherwise it created the exact result that was expected. Here is the query,

More exact solution is much appreciated.

Leave a Reply

Notify of
Close Menu