admin管理员组

文章数量:1122846

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?

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?

Share Improve this question edited May 14, 2024 at 3:24 LBF asked May 14, 2024 at 2:33 LBFLBF 5293 gold badges11 silver badges28 bronze badges 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. – Tony Djukic Commented May 14, 2024 at 23:05
Add a comment  | 

1 Answer 1

Reset to default 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
        

    }

});

本文标签: wp queryOrderby meta value that is saved as an array