I’m searching for a solution for my WordPress custom query problem.
I have a search-form where the user can input some text, this text can be a word from the post_title
or an meta_value (Company ID)
.
I need to search the string in post_title
OR the meta_key-Field
“id-number”,
but I also have some other additional search params.
These are my Args for the WP_Query
:
Array(
[post_type] => company
[pagination] => 1
[posts_per_page] => 10
[paged] => 1
[meta_query] => Array
(
[relation] => AND
[0] => Array
(
[0] => Array
(
[key] => id-number
[value] => FOOBAR
)
[1] => Array
(
[key] => post_title
[value] => FOOBAR
[compare] => LIKE
)
[relation] => OR
)
[1] => Array
(
[relation] => AND
[0] => Array
(
[0] => Array
(
[key] => country
[value] => USA
)
[relation] => OR
)
)
)
)
Array[meta_query][0][1] (post_title)
is only a placeholder – i know that can’t work, but how can i search for
(id-number OR post_title)
AND (all other vars...)
Doing this with WP_Query isn’t directly possible. The query is constructed from the arguments in the monstrous (over 1000 lines long)
WP_Query::get_posts
method (see wp-includes/query.php) as mostly a long series of concatenations ofAND
statements to a$where
variable.1Now, you can hook into a number of filters to customize how that variable (which holds the SQL for the query) is constructed. In your case, one of the following might be appropriate:
Using filter, you’d not really send arguments to WP_Query and construct it in “the normal way” but override how the SQL WHERE query is constructed. You might be better off just running your own SQL query entirely. The codex has an article Displaying Posts using a Custom Select Query that details how this can be done.
1. WP_Query is not at all a complete ORM but a dedicated class for taking query string variables and filtering posts based on those rules.
There’s a ready-to-use copy & paste solution by Adam Balee – and by short I mean 50 lines including comments.
It uses just three simple hooks:
meta_value
fields to the querymeta_value
LIKE % just after thepost_title
LIKE statementTo make happy the stackoverflow purists I will paste Adams’s solutions here but feel free to visit Adam’s blog for detailed explanation.