Can serialized arrays in DB be matched against serialized arrays with meta_query?

Say I have an array of checkbox choices associated with a post (a custom field) stored in the database in serialized form. On my site, I present users with the same checkboxes and let them make their choices to “filter” out posts according to their choices. If as little as one of their choices matches a posts choices, that post should be displayed.

$args['meta_query'] = array(
  array(
    'key' => 'choices',
    'value' => $_POST['choices'],
    'compare' => 'IN',
));

As the data in the DB is in serialized form, I hoped that the WP_Query was smart enough to understand that it needed to unserialize the serialized data in the DB before attempting to match. This was not the case, and I am considering submitting this to the WP Trac and see if it can be added as a feature in future releases.

My question is whether I have any options here, other than to store my data in another way (which at the moment seems difficult as I am using the plugin Advanced Custom Fields to store it). I looked through meta_query with meta values as serialize arrays, and the answers there pointed me towards storing my data in another way. I hope I can avoid that.

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

The one dirty option is using LIKE comparison in meta query request. It will just treat serialized value as string to make substring match against. It won’t be my first (or second) approach to rely on, but in some cases I had to do it like this.

Non-unique meta keys are a little tricky to work with, but they are much better way to store stuff you want to query by.


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