Use Query search full name: first name AND last name

I needed the WP search to be able to find first name AND last name, not OR. 'John Doe' should return John Doe. I have found something here, it has a good idea, but it cannot find "John Doe", only all Johns and all Does. So I have extended this solution. I answer my own question. Here is my code...you can find "John Doe" now. add_action( 'pre_user_query', function( $uqi ) { global $wpdb; $search = ''; if ( isset( $uqi->query_vars['search'] ) ) $search = trim( $uqi->query_vars['search'] ); if ( $search ) { $search = trim($search, '*'); if (stristr($search, " ")) { $search_exp = explode(" ", $search); // 1. Query: Vorname $query1 = "SELECT * FROM wp_usermeta WHERE meta_key = 'first_name' AND meta_value LIKE '%".$search_exp[0]."%'"; $results1 = $wpdb->get_results($query1); $vorname_ids = array(); foreach ($results1 as $key1 => $value1) { $vorname_ids[] = $value1->user_id; } // 2. Query: Nachname $query2 = "SELECT * FROM wp_usermeta WHERE meta_key = 'last_name' AND meta_value LIKE '%".$search_exp[1]."%'"; $results2 = $wpdb->get_results($query2); $nachname_ids = array(); foreach ($results2 as $key2 => $value2) { $nachname_ids[] = $value2->user_id; } $fullname_ids = array_intersect($vorname_ids, $nachname_ids); $fullname_ids = implode(",", $fullname_ids); $search_meta = $wpdb->prepare(" ID IN ('%s')", $fullname_ids); $uqi->query_where = str_replace( 'WHERE 1=1 AND (', "WHERE 1=1 AND (" . $search_meta . " OR ", $uqi->query_where ); } else { $the_search = '%'.$search.'%'; $search_meta = $wpdb->prepare(" ID IN ( SELECT user_id FROM {$wpdb->usermeta} WHERE ( ( meta_key='first_name' OR meta_key='last_name' OR meta_key='billing_city' ) AND {$wpdb->usermeta}.meta_value LIKE '%s' ) )", $the_search); $uqi->query_where = str_replace( 'WHERE 1=1 AND (', "WHERE 1=1 AND (" . $search_meta . " OR ", $uqi->query_where ); } } });

Comment (0)

You’ll be in good company