Reputation: 739
I am trying to write a user search query, i have location and searching keyword (user name)
i need to search all user, with last name or first name matches to searching keyword for a specified loaction my code here,
$args = array(
'meta_query' => array(
'relation' => 'AND',
0 => array(
'key' => 'last_name',
'value' => $search_string,
'compare' => 'LIKE'
),
1 => array(
'key' => 'first_name',
'value' => $search_string,
'compare' => 'LIKE'
),
2 => array(
'key' => 'user_city',
'value' => $Location,
'compare' => 'LIKE'
),
),
);
$users = new WP_User_Query( $args);
$users = $users->get_results();
but i want 'relation' OR for first name and last name and relation AND for location, how i can do it ?
Upvotes: 3
Views: 2145
Reputation: 403
please use
$args = array( 'meta_query' =>
array(
array(
'relation' => 'OR',
array( 'key' => 'last_name', 'value' => $search_string, 'compare' => 'LIKE' ),
array( 'key' => 'first_name', 'value' => $search_string, 'compare' => 'LIKE' ),
),
array( 'key' => 'user_city', 'value' => $Location, 'compare' => 'LIKE' ), ),
);
Upvotes: 1
Reputation: 31
Try this
$user_ex = explode(' ', $search_string);
if($user_ex[1]) {
$name_array = preg_split("/[\s,]+/", $search_string_user);
$args = new WP_User_Query( array(
'meta_query' => array(
'relation' => 'OR',
array(
'relation' => 'OR',
array(
'key' => 'user_city',
'value' => $search_string,
'compare' => 'LIKE'
),
),
array(
'relation' => 'AND',
array(
'key' => 'first_name',
'value' => $name_array[0],
'compare' => 'LIKE'
),
array(
'key' => 'last_name',
'value' => $name_array[1],
'compare' => 'LIKE'
),
),
),
}
Upvotes: 0
Reputation: 340
I believe it's not possible to have multiple relation fields in a wp_query. Please reference https://codex.wordpress.org/Class_Reference/WP_User_Query.
As an alternative, you can look into pre_user_query, which is a hook to call a function before the query is called.
add_filter( 'pre_user_query', 'some_function' );
function some_function () {
//do custom query altering here.
}
Upvotes: 0