user774105
user774105

Reputation: 101

Wordpress query with several meta values as condition

First time using wordpress query so not sure how to handle this problem. I want to get post titles where meta_key is 'tag' and meta_values are 'A, B, C'. Something similar to IN() function of sql query. How should I do to achieve that?

This is my code so far but it is not working as it ignores condition.

 //$tags consists of my meta_value ( A, B, and C) 
    foreach ($tags as $input) {


    $data[] = array( 'meta_key' => 'tag', 'meta_value' => $input, 'orderby' => 'post_date' ); 


    }




        $query = new WP_Query( $data );

Thanks in advance for your kind help.

Upvotes: 0

Views: 1828

Answers (2)

user774105
user774105

Reputation: 101

Here is the answer:

$args = array(

    'meta_query' => array(
    array(
        'key' => 'tag',
        'value' => $tags,
        'compare' => 'IN'
        ) 
    ),

    'orderby' => 'post_date'    

);

Upvotes: 1

Jason McCreary
Jason McCreary

Reputation: 73041

Read the Custom Field Parameters section on the WordPress Codex for WP_Query.

The problem is you are rebuilding your entire $data array on each loop. This passes invalid parameters to WP_Query. So I imagine your getting undefined results.

You simply want to set meta_value directly or specify a meta_query parameter similar to the IN clause you described.

Upvotes: 2

Related Questions