Query multiple meta key values?

How to query for mutiple meta key values with the same key

$querystr = "  
            SELECT $wpdb->posts.* 
            FROM $wpdb->posts, $wpdb->postmeta
            WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 

            AND $wpdb->postmeta.meta_key = 'key1'   
            AND $wpdb->postmeta.meta_value="value1"
            // why doesn't this work?
            AND $wpdb->postmeta.meta_value="value2"

            AND $wpdb->posts.post_status="publish" 
            AND $wpdb->posts.post_type="post"
            ORDER BY $wpdb->posts.post_date DESC
                ";

next code

<?php 
$args = array(
    'meta_query' => array(
        array(
            'key' => 'key1',
            'value' => 'value1',
            'compare' => '='
        ),
// this array results in no return for both arrays
        array(
            'key' => 'key1',
            'value' => 'value2',
            'compare' => '='
        )
    )
);
$the_query  = new WP_Query( $args );
 ?>

                <?php /* Start the Loop */ ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

                    <?php get_template_part( 'content', get_post_format() ); ?>

                <?php endwhile; ?>

4

I feel like there’s an AND/OR confusion going on here.

The queries in the OP will only return posts which have both key1 = ‘value1’ AND key2 = ‘value2’. Most WP plugins (that I know of, anyway) do not store multiple values in postmeta, for the same post, using the same key.

If what you want is really an OR (you want to get the posts where key1 = ‘value1’, as well as the posts where key1 = ‘value2’), then see @WhiskerSandwich’s answer, using ‘IN’ and an array of values for the value parameter.

Alternatively, you can provide a relation parameter to `meta_query’:

$args = array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'key1',
            'value' => 'value1',
            'compare' => '='
        ),

        array(
            'key' => 'key1',
            'value' => 'value2',
            'compare' => '='
        )
    )
);

Note that using OR as the relation for multiple meta queries using the same key is the functional equivalent of using IN and an array of values for a single one.

Leave a Comment