1

Let's say I have categories (cat1, cat2) and I have postmeta keys (date1, date2, status).

How do I view all posts in all categories with these filters:

  • For cat1, I want to apply WHERE date2 <= $today.
  • For cat2, I want to apply WHERE status=1.

How do I apply the $args for WP_Query?

1 Answer 1

0

I don't think there's an easy way to do that with a single query. WP_Query is very good at taxonomy queries nowadays, even doing things like nested comparisons, and custom field queries. In your case, you're trying to limit the posts returned by a meta query when another condition is true. If you go and grab only the IDs from the first two queries, you can run a third query that's very cheap to return the entire result with perfect formatting for the loop.

First, run the first meta & tax query.

<?php 
$today = date();
$args1 = array(
    'fields' => 'ids',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'cat1',
        ),
    ),
    'meta_query' => array(
        array(
            'key'     => 'date2',
            'value'   => $today,
            'compare' => '>=',
        ),
    ),
);
$query1 = new WP_Query( $args1 );

Next, run the second meta & tax query.

$args2 = array(
    'fields' => 'ids',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'cat2',
        ),
    ),
    'meta_query' => array(
        array(
            'key'     => 'status',
            'value'   => 1,
            'compare' => '=',
        ),
    ),
);
$query2 = new WP_Query( $args2 );

Finally, combine the two results and run a third query for just the resulting post's IDs.

$all_IDs = array_merge( $query1->posts, $query2->posts );

$final_query = new WP_Query( array( 'post__in' => $all_IDs ) );

h/t Bora Yalcin's answer for the query combination

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.