Search user by custom fields ( user_meta ) in the

2020-04-20 06:51发布

问题:

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>

回答1:

Two errors you have in your code.

  1. mentioned in the comment by @cabrerahector: you should remove all * from your meta_query value's.
  2. You're trying to use search here:

    'role' => 'Subscriber', 
    'search' => '*' . $search . '*',
    

    But the problem is that search key will always try to find your $search from email address, URL, ID, username or display_name of your wp_users table with relation AND. 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:

$search = ( isset($_GET['search-meta']) ) ? sanitize_text_field($_GET['search-meta']) : false ;

if ($search){

    $my_users = new WP_User_Query(

        array(
            'role' => 'Subscriber',
            'fields'     => 'all',
            'meta_query' => array(
                'relation' => 'OR',
                array(
                    'key'     => 'institution',
                    'value'   => $search,
                    'compare' => 'LIKE'
                ),
                array(
                    'key'     => 'equipment',
                    'value'   => $search,
                    'compare' => 'LIKE'
                )
            )

        ));

}