I’ve build several search forms with different <select>
and <input>
.
I use a meta_query
and build an array of key/value pair.
Array
(
[relation] => AND
[0] => Array
(
[relation] => AND
[0] => Array
(
[fields] => ID
[key] => ville
[value] => Angers
[compare] => LIKE
[type] => CHAR
)
)
[1] => Array
(
[relation] => OR
)
[2] => Array
(
[relation] => OR
)
)
It works, i can filter users or posts (i use WP_User_Query
or WP_Query
).
The search form is using AJAX, it means that each time a user change a select
, the $query_array
is updated and the list of results is also updated.
So, let’s say the default value of a select is 0
<option selected="" value="0"> -- City -- </option>
In this case, i reset the meta_key / meta_value :
if (!empty($_POST['city']) && $_POST['city'] != '0') {
$meta_value_ville = $_POST['city'];
array_push($query_array_and, array('fields' => 'ID', 'key' => 'ville', 'value' => $meta_value_ville, 'compare' => 'LIKE', 'type' => 'CHAR'));
} else if ($_POST['city'] === '0') {
// reset
array_push($query_array_and, array('fields' => 'ID', 'key' => '', 'value' => '', 'compare' => 'LIKE', 'type' => 'CHAR'));
}
I empty the key and the value.
The result is
Array
(
[relation] => AND
[0] => Array
(
[relation] => AND
[0] => Array
(
[fields] => ID
[key] =>
[value] =>
[compare] => LIKE
[type] => CHAR
)
)
[1] => Array
(
[relation] => OR
)
[2] => Array
(
[relation] => OR
)
)
Is it the best way to do it ? I feel that sometime the list of posts or users is not complete with this method.