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.

Here are the args for my query :

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

This works when topics is a string, but not when it is an array. I'd like this query to work when topics is for example array( 'sports', 'nonprofit', etc. )

Is there a way to build meta queries with arrays as a meta_key ?

share|improve this question
    
Please clarify--do you mean that the stored value of "topics" is an array? Or that the stored value is a string, and you want to pass multiple terms to the query in an array? –  MathSmath Jun 15 '12 at 14:03
    
@MathSmath, I mean that the stored value is an array. –  mike23 Jun 15 '12 at 14:08

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer

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.