How do I search Membership users by name?

Hi there,
Is the members in the membership system available to search by name. So far we can only get it searchable by username or email.

Thanks,

Brielle

  • Ash

    Hello @jakilevy

    I hope you are well today and thanks for asking the question.

    Please use the following code in your functions.php

    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);
       }
    }

    Now the search should work with first name or last name or first name + last name.

    Please let me know if it is helpful and feel free to ask more question if you have.

    Cheers
    Ash

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.