I'm trying to compare user meta values to find highest and lowest values. I have a user meta value set up called "hourly_rate". I want to get the hourly rate for all users and then run PHP's min()
and max()
on these values to find the lowest and highest hourly rates across all of my users.
Currently, I'm doing this by getting all users from the database and iterating through a foreach loop, grabbing the specific meta key for each user and stashing it in an array. Then I run min and max on that array.
As the site scales in users, this seems like it could become quite cumbersome just to find a min and max value. Is there a way I can do something like get_user_meta()
by key instead of ID?
For example, I currently do this:
$users = new WP_User_Query(array(
'order' => 'DESC',
'fields' => 'all_with_meta'
));
$hourly_rates_array = array();
foreach($users->results as $user){
$hourly_rate = get_user_meta($user->ID, 'hourly_rate', true);
array_push($hourly_rates_array, $hourly_rate);
}
//Find the necessary limits for each user
$lowest_hourly_rate = min($hourly_rates_array);
$highest_hourly_rate = max($hourly_rates_array);
Is there a way I could do something like this:
$hourly_rates_array = get_user_meta('ALL', 'hourly_rate', true);
$lowest_hourly_rate = min($hourly_rates_array);
$highest_hourly_rate = max($hourly_rates_array);
Which would access the wp_usermeta table directly instead of bouncing through wp_users and then wp_usermeta? This would drastically cut my DB queries and be much better for performance, but I can't seem to figure out a way to get user_meta by key instead of by user ID.