Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
    
Feature requested on Trac: core.trac.wordpress.org/ticket/18410. –  Doggie52 Aug 15 '11 at 11:56
1  
the problem is that SQL does the querying, but only PHP understands the serialization, you'd have to select then unserialize EVERY meta field with a matching key and check it for a match. don't store them serialized is the answer. –  Milo Aug 15 '11 at 14:34

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Ah, did not think of that. I ended up matching posts using the actual unserialized array and not meta_query, somewhat more ineffecient but at least it works! Another way would have been to manually query the database using WP_Query, I suppose. –  Doggie52 Aug 17 '11 at 11:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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