Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm having issues ordering a loop of users by a custom meta_value. Reading the Codex for get_users(), it doesn't actually say that you can use the meta_value for orderby. When I try to do it I get a list of users not ordered by the meta_value.

<ul>
<?php
$args = array(
'role' => 'author' ,
'meta_key' => 'score',
'orderby' => 'meta_value_num',//Tried meta_value also
'order' => 'DESC',
'number' => 5,
);
$blogusers = get_users($args);
foreach ($blogusers as $user) {
    echo '<li>' . $user->display_name . '</li>';
    echo get_user_meta($user->ID, 'score',true);
}
?>
</ul>    

So what I need to do is override the orderby function by hooking into the pre_user_query. I found this snippet but was told not to use create_function. So what is the right way to do this to order a list of users by user meta_value?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Try this code, but replace METAKEY to the key-name of your metadata.

<?php 
function cmp( $a, $b )
{ 
  if(  $a->METAKEY ==  $b->METAKEY ){ return 0 ; } 
  return ($a->METAKEY < $b->METAKEY ) ? -1 : 1;
} 

?>

<ul>
<?php
$args = array(
'role' => 'author' ,
'meta_key' => 'METAKEY',
'number' => 5,
);
$blogusers = get_users($args);
usort($blogusers ,'cmp');

foreach ($blogusers as $user) {
    echo '<li>' . $user->display_name . '</li>';
    echo get_user_meta($user->ID, 'METAKEY', true);
}
?>
</ul>
share|improve this answer
    
This created the same ordered list of users. What is the purpose of that function exactly and how do I order the list? –  Pollux Khafra Jun 20 '12 at 18:30
    
The magic is in function cmp. By changing return (... > ...) ... to return (... < ...) ... you will change the order. –  Maxim Orlovsky Jun 21 '12 at 8:21
    
I had just finally found this method here too clarklab.com/posts/… ...Got it working great TY! –  Pollux Khafra Jun 21 '12 at 9:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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