两个选项。第一种方法将使您远离自定义SQL,并且应该比您当前拥有的更高效。
它运行两个查询,一个是获取小时费率最高的用户ID,另一个是获取小时费率最低的用户ID。您还需要一个查询来更新用户元缓存;那么你就可以自由回家了:
$query = new WP_User_Query;
$users = array(
\'min_user\' => \'ASC\',
\'max_user\' => \'DESC\',
);
foreach ( $users as $var => $order ) {
$query->query(
array(
\'count_total\' => false, // Save SQL_CALC_FOUND_ROWS, don\'t need it
\'meta_key\' => \'hourly_rate\',
\'orderby\' => \'meta_value\',
\'fields\' => \'ID\', // Don\'t waste memory
\'number\' => 1, // Just need the first user ID of the result
\'order\' => $order,
)
);
if ( $data = $query->get_results() )
$$var = $data[0]; // User ID
else
$$var = 0;
}
update_meta_cache( \'users\', array( $min_user, $max_user ) );
echo get_post_meta( $max_user, \'hourly_rate\', true ); // Highest hourly rate
echo get_post_meta( $min_user, \'hourly_rate\', true ); // Lowest hourly rate
第二个是一个自定义SQL查询:
$rates = $wpdb->get_row( "SELECT MAX( CAST( meta_value AS UNSIGNED ) ) AS max_rate, MIN( CAST( meta_value AS UNSIGNED ) ) AS min_rate FROM $wpdb->usermeta WHERE meta_key = \'hourly_rate\'" );
echo $rates->max_rate;
echo $rates->min_rate;
没有比这更瘦的了!