0

I want to order a WP_User_Query by a meta value. The meta key is a multi-select field, and the value is saved as an array.

When I do a print_r of get_user_meta($user_id,'committee',true) this is what I get:

Array ( [0] => Restoration )

Or

Array ( [0] => Historian [1] => Conservation )

How can I order alphabetically by this value when it is an array? Doing a normal orderby like this does not work:

'meta_key'   => 'committee',
'orderby'    => 'meta_value',
'order'      => 'ASC'

When I do an export of all user meta, I see that the values are stored as a serialized array in the database.

Is it possible?

1
  • Sometimes when I encounter complex sorting and ordering like this, I instead hide the results, sort them using javascript once everything is separated out and then have it animate into view. Depending on the quantity of the data, it's usually pretty quick and painless. Commented May 14 at 23:05

1 Answer 1

3

I don't think it will be possible using the User Query Class and probably not through MySQL either, because WordPress saves Arrays as Serialized data, so MySQL can't interpret it like it could if it was a JSON format.

The only solution I can foresee is ordering it yourself using a loop in PHP - just query all users, then get it's metadata, and loop through it ordering as you need.

To get best of performance, you can create an array containing the ordered IDs of the users, and save it as an option - or transient - and rebuilding this order index every time the user meta is changed. Something like this:

add_action( "added_user_meta", function($mid, $object_id, $meta_key, $meta_value) {

    if ($meta_key == 'meta_key_you_are_ordering_by') {

        //Get all users and loop through meta
        

    }

});
1
  • 1
    Thank you. I was afraid this was the case!
    – LBF
    Commented May 14 at 16:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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