If you’ve ever tried to retrieve users by a display name, as I have, and tried to use get_users you’ve inevitably ended up grabbing all the users and then looping through them after the fact. That takes too long when we just want the users who’s display names match what we’re looking for. For that, we need to use some SQL logic.
<?php global $wpdb; $search = 'Pat'; $users = $wpdb->get_results("SELECT ID, display_name FROM $wpdb->users WHERE display_name LIKE '%$search%' ORDER BY display_name"); print_r($users); ?>
The preceding snippet will get the IDs and display_names of all users from the wp_users ($wpdb->users) table with a display_name that contains a text variable (%$search%) which in this case is Pat. Printing the array below gives me the following results:
This is coming from a project containing about 2200 users. Obviously filtering through 2200 results isn’t ideal, especially when AJAX gets involved (shitty user experience and all, ya know). By querying the database myself I’ve returned less than 100 results, speeding things up considerably. SQL is an invaluable tool, use it well and learn it – don’t rely on WordPress’ queries and functions as they’re pretty bloated. In an effort to make them idiotproof they’re also less useful than a self-made query.