I have a custom USER taxonomy called ‘label’ which also has a custom field of ‘sort_order’ – I am trying to return a list of users that have the label taxonomy and then sort this list by the sort_order field.
So far I have…..
<?php
$users = get_users(
array(
'meta_key' => 'sort_order',
'fields' => 'all_with_meta'
)
);
function wpse98580_sort_order( $a, $b )
{
if ( $a->sort_order === $b->sort_order ) {
return 0;
} elseif ( $a->sort_order > $b->sort_order ) {
return -1;
}
return 1;
}
usort( $users, 'wpse98580_sort_order' );
/* Iterate over the sorted array */
foreach( $users as $user )
{
echo '<h4>' . $user_info-> user_firstname . ' ' . $user_info-> user_lastname . '</h4>';
}
?>
This doesn’t work, I am assuming it is becasue the ‘sort_order’ meta-key is actually a custom field of the taxonomy so it can’t retrieve it. Usually I use the following code to access the sort_order…
$product_terms = wp_get_object_terms($user->ID, 'label');
if(!empty($product_terms)){
if(!is_wp_error( $product_terms )){
foreach($product_terms as $term){
$t_ID = $term->term_id;
$label_custom_fields = get_option("taxonomy_term_$t_ID");
echo $label_custom_fields['sort_order'];
}
}
}
Can anyone help?
By using this you can get your result in ascending order for sort_order custom field
Unfortunately, it does not take
meta_value
ormeta_value_num
as a value for theorderby
parameter, as its post-related companions do.But we can specify to only grab those with a value for the meta_key
sort_order
set:get_users()
returns an array of user objects (instances of theWP_User
class).Though a
var_dump
of one of those objects will not reveal it, metadata of the user is accessible as a property thanks to the class’s magic methods.Hence – though untested – the following should sort the users the way you desire:
For reference, see
usort
.There is an action that should do this. It doesn’t seem to be very documented but
pre_user_query
does show up in source.That will sort the query on the meta key if the key is set, which is probably too aggressive but you can add more conditions. This is minimally tested with values in my database but it does appear to work (fairly sure). There are two versions of that query. The second will
CAST
yourmeta_value
to anINTEGER
so you should get decent numeric sorting.Barely tested. Possibly buggy. Caveat emptor. No refunds.