How to search WordPress users’ first name and last name

Posted by Lloyd
Last updated
MySql WordPress query

Finally!

Here’s a way of accurately searching by first name and last name – and it works!

I created this to solve a client solution, and wanted to share this snippet of code to save you some time.

The below code assumes that we want to search users in the ‘agent’ user level by first_name and last_name. You can change ‘agent’ to any inbuilt user level in WordPress, or remove that part entirely.

To use this code, just paste it in at the bottom of your functions.php file, or in a custom plugin.

Call it however you like / in whatever context.

function search_users($search_term){
		
		global $wpdb;
		$the_users = $wpdb->get_results("SELECT DISTINCT $wpdb->users.* FROM $wpdb->users INNER JOIN $wpdb->usermeta um1 ON um1.user_id = $wpdb->users.ID JOIN $wpdb->usermeta um2 ON um2.user_id = $wpdb->users.ID WHERE (um1.meta_key = 'uRPhICRS_capabilities' AND um1.meta_value LIKE '%agent%') AND ((um2.meta_key = 'first_name' OR um2.meta_key = 'last_name') AND um2.meta_value LIKE '%".$search_term."%');");

		if(!empty($the_users)){
			return $the_users;
		}
		else{
			return false;
		}
		
	}

Leave a Reply

Your email address will not be published. Required fields are marked *