3

I want give OR relation between tax_query and meta_query:

$post_args = array('post_type' => 'post',
    'order'     => 'DESC',
    'meta_query' => array(
     'relation'  => 'OR',
          array(
            'key' => 'client_segment',
            'value' =>$client ,
            'compare' => 'IN',
          ),
          array(
                'key'  => 'filtered_date',
                'value'=> array($start_date, $end_date),
                'compare'   => 'BETWEEN'
            )
        ),
        'tax_query' => array(
        'relation' => 'OR',
        array(
            'taxonomy'  => 'category',
            'field'     => 'id',
            'terms'     => $term_id,
            'operator'  => 'IN')

            ),
);

$posts = new WP_Query($post_args);  

What is wrong with my code?

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
Vysakh
  • 93
  • 1
  • 11

2 Answers2

4

Put your meta_query after the tax_query and wrap the WP_Query with 'get_meta_sql' filter, then replace first AND with OR, as below:

add_filter('get_meta_sql', 'filter_query', 10, 1);
$posts = new WP_Query($post_args);
remove_filter('get_meta_sql', 'filter_query');

Then the filter function, which replaces the first AND with OR:

function filter_query($sql){
    $pos = strpos($sql['where'], 'AND');
    if ($pos !== false) {
        $sql['where'] = substr_replace($sql['where'], 'OR', $pos, strlen('AND'));
    }
    return $sql;
}

This is faster and saves you the time filtering the duplicates after merging the queried posts.

Naji Amer
  • 61
  • 1
  • 3
2

There is no way to give OR relation between two queries, but what you can do to make two separate queries and then merge the results of them.

Because basically you need results of both of these queries.

You can find solution how to merge 2 queries in this post