0

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?

1

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>
  • 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. – MaximOrlovsky 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

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.