Search user by custom fields ( user_meta ) in the front end

后端 未结 1 728
野性不改
野性不改 2021-01-25 14:03

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 nee

相关标签:
1条回答
  • 2021-01-25 14:35

    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'
                    )
                )
    
            ));
    
    } 
    
    0 讨论(0)
提交回复
热议问题