Possible to get posts from multiple meta keys/values in a single query?

Say I have a bunch of posts, some of them have a meta key called “key1” and some of them have a meta key called “key2”. But the posts do not have both.

I’d like to create a custom query which retrieves any post that has “key1” or “key2” as a meta key. (not a single post which has both).

After digging around, the closest I’ve got to (for a single query) was using the meta_query array which allows me to query for posts that have multiple meta keys. However I am looking for posts OF multiple meta keys.. ie: if it has key1 or key2, load up the query.

Aside from the above, the only other way I can seem to query for posts that have either key1 or key2 is to create multiple queries and loops. I’m wondering if there’s a cleaner solution. My ideal end-result would be to have the resulting post mixed in with each other and displayed as if it came from a single query. With multiple queries I feel I wont be able to achieve this as I will get the results with key1 first and then the results with key2 afterwards in the next query/loop.

Thanks in advance!

2 Answers
2

An easy query like the following should work for you:

<?php
$_query = new WP_Query( array(
        'post_type'         => 'post',
        'posts_per_page'    => -1,
        'post_status'       => 'publish',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'key1'
            ),
            array(
                'key'     => 'key2'
            ),
        ),
    ) );
?>

Note the 'relation'=>'OR' in meta_query.

More at:

  • WP_Query – Custom Fields
  • WP_Meta_Query

Leave a Comment