membership search lack of last name

when viewing "All Members" in the admin panel and doing a search it seems that "last names" are not relevant.

Example:
Member name "John Doe"

Search in "All members" for John... get results
Search in "all members" for Doe... get no results.

Is this a bug?

  • Michael Bissett

    Hey @Andrew Nugent-Head, hope you're doing well today! :slight_smile:

    You would need to use an asterisk if you're going to do a last name search, like this:

    *Doe

    Alternatively, you can create an mu-plugin, and insert the following code into it:

    add_action('pre_user_query','mam_pre_user_query');
    function mam_pre_user_query($user_search) {
       global $wpdb;
       $vars = $user_search->query_vars;
       if (!is_null($vars['search'])) {
          $search = preg_replace('/^\*/','',$vars['search']);
          $search = preg_replace('/\*$/','',$search);
          $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m1 ON " .
             "{$wpdb->users}.ID=m1.user_id AND (m1.meta_key='first_name')";
          $user_search->query_from .= " INNER JOIN {$wpdb->usermeta} m2 ON " .
             "{$wpdb->users}.ID=m2.user_id AND (m2.meta_key='last_name')";
          if (preg_match('/^byname:/',$search)) {
             $search = preg_replace('/^byname:/','',$search);
             $user_search->query_orderby = ' ORDER BY UPPER(m2.meta_value), UPPER(m1.meta_value) ';
             $user_search->query_vars['search'] = $search;
             $user_search->query_where = str_replace('byname:','',$user_search->query_where);
          }
          $names = explode(' ',$search,2);
    	if(count($names) > 1){
    	    $first_name = $names[0];
    	    $last_name = $names[1];
    	    $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s' OR (m1.meta_value LIKE '%s' AND m2.meta_value LIKE '%s')", "%{$search}%","%$search%","%$first_name%","%$last_name%");
    	}else{
    	   $names_where = $wpdb->prepare("m1.meta_value LIKE '%s' OR m2.meta_value LIKE '%s'", "%{$search}%","%$search%");
    	}
          $user_search->query_where = str_replace('WHERE 1=1 AND (',
             "WHERE 1=1 AND ({$names_where} OR ",$user_search->query_where);
       }
    }

    (originally posted on this thread: https://premium.wpmudev.org/forums/topic/how-do-i-search-membership-users-by-name#post-556117)

    Hope this helps! :slight_smile:

    Kind Regards,
    Michael

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.