I wouldn’t push the meta query entries like that but build it more logical.
So for example:
$meta_query_args = array( 'relation' => 'AND' ); // assuming you want 'AND' search, you're using both in your example
if ( ! empty( $_POST['city'] ) && $_POST['city'] != '0' ) {
$meta_value_ville = $_POST['city'];
$meta_query_args['city_clause'] = array(
'key' => 'ville',
'value' => $meta_value_ville,
'compare' => 'LIKE',
'type' => 'CHAR'
);
}
// Example, say you also have a country field
if ( ! empty( $_POST['country'] ) && $_POST['country'] != '0' ) {
$meta_value = $_POST['country'];
$meta_query_args['country_clause'] = array(
'key' => 'country',
'value' => $meta_value,
'compare' => 'LIKE',
'type' => 'CHAR'
);
}
Note 1: I’m no longer pushing date into existing arrays build build it from scratch every time. This saves you all the code of resetting certain meta query arrays.
Note 2: I removed the 'fields' => 'ID'
part since this isn’t part of the meta_query. You should add this to the WP_Query
.
Note 3: Because I’m giving the clauses named index (e.g. city_clause
) you can use them in the rest of your WP_Query
. Example: You can sort on them now like this:
$q = new WP_Query( array(
'meta_query' => $meta_query_args,
'orderby' => 'city_clause'
) );