How can I create a meta_query with an array as meta_field?

Feeding the query an array of possible values

If the value in the database is a string and you want to feed the query several values:

$args = array(
    'post_type' => 'news',
    'meta_query' => array(
        array(
            'key' => 'topics',
            'value' => array ( 'sports', 'nonprofit', 'community' ),
            'compare' => 'IN'
        )
    )
);

Searching for a specific value in a serialized array of data

If the value in the database is an array of several topics and you want to search for a single topic within that array (Note that an array in the database can be retrieved as such, but lives in the database in serialized form, which is a string also):

$args = array(
    'post_type' => 'news',
    'meta_query' => array(
        array(
            'key' => 'topics',
            'value' => 'sports',
            'compare' => 'LIKE'
        )
    )
);

Using ‘LIKE’ as the compare value isn’t as clear-cut an instruction as you might have hoped for, but it is the best option to go with.

Next to that, your only other option would be retrieving all posts that have the meta_key “topics” set and iterating over them manually or,in other words, check for the value within the loop and display the posts on said condition.

EDIT 2021

Though still valid, the above answer is 9 years old.
Have a look at @sMyle’s and at @Kaji’s excellent answers as well.

Leave a Comment