I have a large amount of users which I'm displaying on the front end with WP_User_Query
.
I have a search function on this front end user database, and need to be able to search by custom fields, which each profile has a number of.
Currently the search engine will search for standard wp user fields such as 'user_firstname', 'user_lastname', but won't search my custom fields ('institution' & 'equipment' in this example), and I'm not sure why.
The Query:
$search = ( isset($_GET['search-meta']) ) ? sanitize_text_field($_GET['search-meta']) : false ;
if ($search){
$my_users = new WP_User_Query(
array(
'role' => 'Subscriber',
'search' => '*' . $search . '*',
'fields' => 'all',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'institution',
'value' => '*' . $search . '*',
'compare' => 'LIKE'
),
array(
'key' => 'equipment',
'value' => '*' . $search . '*',
'compare' => 'LIKE'
)
)
));
}
The Search Form:
<form method="get" id="db-search" action="<?php the_permalink() ?>">
<input type="text" class="field" name="search-meta" id="s" placeholder="Search Database" />
<button type="submit"><i class="fa fa-search"></i></button>
</form>
Two errors you have in your code.
*
from yourmeta_query
value
's.You're trying to use
search
here:But the problem is that
search
key will always try to find your$search
from email address, URL, ID, username or display_name of yourwp_users
table with relationAND
. This mean, that if your$search
will not match with one of the mentioned columns, then your query will return nothing.Here is working code to search from
meta_values
of users: