Initially I thought I’d use get_users()
but it turned out it doesn’t support the display_name field. Then I’ve read about using WP_User_Query, but when I do it always exhausts the allowed memory size of 134217728 bytes. When I remove the memory limit this part of the page doesn’t even try to load. Now I’m thinking about running a function that adds everyone’s display_name to their user meta so I can use get_users()
again. Is that a good idea?
My objective is to make the search also sort by relevance and I plan to do it by using explode(' ', $search_query)
then call get_users()
for each element in the array, then combine and sort the results by occurance like it’s shown here: https://stackoverflow.com/questions/2176626/php-get-element-with-5-highest-occurrence-in-an-array and I’m not sure if that’s going to be memory efficient.
Thanks for reading.
2 Answers
I think you should use the default class for this job – WP_User_Query
.
The query have a lot of possibilities, also get the display name. WP_User_Query is a class that allows querying WordPress database tables _users
and _usermeta
.
Also it is helpful when you use a cache for the values. Also here I prefer the WordPress defaults WP_Cache
(Non-Persistent Cache) or transient API (Database-Driven Temporarily Persistent Cache).
The example below will demonstrate this with WP_Cache, you can also doing this with transients. The code will not work, is only write by scratch to illustrate.
function wpse_get_user_data( $args ) {
if ( ! $user_query = wp_cache_get( $args->ID, 'your_key' ) ) {
$user_query = array();
$user_query = new WP_User_Query( $args );
wp_cache_add( $args-ID, $user_query, 'your_key' );
}
return $user_query;
}