I have a serialized array as a meta value and I’m trying to run WP Query where it finds a specific value in the serialized array.

Here’s an example of the serialized array field:

a:6:{i:0;s:3:"173";i:1;s:3:"172";i:2;s:3:"171";i:3...

Here’s my query, but it doesn’t work:
The ID’s are numberic I’m doing a search for as well.

$practiceArgs = array(
    'post_type' => 'attorney',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_query' => array(
                        array(
                              'key' => 'practice_area',
                              'value' => $post->ID,
                              'compare' => 'LIKE',
                              'type' => 'NUMERIC'
                              )
                        )
);

I’ve tried using 'value' => '%'.$post-ID.'%' in my queries, but it doesn’t seem to work as well.

Anyone ever had any experience working on this?

4 Answers
4

I came across this same issue today. In both our situations, there is in fact a nice solution. Because the serialized data we are searching for, are simply IDs, and they are always wrapped in quotations, we just need to include the quotations as part of the query. This eliminates the problem of encountering false positives in the search results.

You just need to modify the meta query to as follows:

array(
    'key' => 'practice_area',
    'value' => '"'.$post->ID.'"',
    'compare' => 'LIKE',
)

This way, it searches for the whole ID, including the double quotes before and after it within the serialized array. No false positives will be included.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *