order by meta_value serialized array

Hi I’m trying to pull posts using the wp query. Just one problem–I am trying to sort the posts alphabetically by a certain meta_value. Thing is that this meta_value is a serialized array. Is there an easy way to do this without having to unserialize it? Thanks!

a:1:{i:0;a:1:{s:7:"people";s:16:"Tanya Garca";}}

Btw, I cannot change the way the meta_value is being saved because I am using this plugin which automatically saves it serialized.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Is there an easy way to do this without having to unserialize it?

Not in any reliable way. You can certainly ORDER BY that value but the sorting will use the whole serialized string, which will give you technically accurate results but not the results you want. You can’t extract part of the string for sorting within the query itself. Even if you wrote raw SQL, which would give you access to database functions like SUBSTRING, I can’t think of a dependable way to do it. You’d need a MySQL function that would unserialize the value– you’d have to write it yourself.

Basically, if you need to sort on a meta_value you can’t store it serialized. Sorry.

If you can’t change how the value is stored you will need to pull your posts, loop through them to sort them, then loop through them again to display the sorted results.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x