1

Each user in system has meta key called points

I need to get top 10 users (highest points)

How I can do this query ?

Should I use get_users() with $args OR native query

  • You should use get_users() with $args! And what do you mean by Native query ? – Sumit Mar 28 '16 at 10:02
  • i mean t $wpdb->get_results() – Sameh Serag Mar 28 '16 at 10:04
  • @Sumit Could u please post an example of the code how it can be done ? – Sameh Serag Mar 28 '16 at 10:04
6

You can use get_users() with meta_key and order by meta value, descending.

Example:

$user_args = array(
    'meta_key' => 'points',
    'number' => 10,
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
);

$top_users = get_users($user_args);

NOTE: Support for meta_value_num is available only from version 4.2

  • 1
    An addendum to this answer, answering OP's question on "using get_users() or $wpdb->get_results()": if possible, don't use raw SQL queries to perform operations that WordPress supports natively. There are several reasons for this: (1) it prevents WordPress from applying filters to the return value, thereby interrupting native functionality; (2) it can yield unexpected results because certain clauses that WordPress includes are not included in your custom SQL; (3) it prevents possible caching and (4) when WordPress changes its internal functionality, you don't want your code to break. – engelen Mar 28 '16 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.