How to give OR relation in tax_query and meta_query Wordpress

时间:2017-05-02 09:49:31

标签: wordpress

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?

2 个答案:

答案 0 :(得分:1)

无法在两个查询之间给出OR关系,但是您可以做两个单独的查询然后合并它们的结果。

因为基本上你需要这两个查询的结果。

您可以找到解决方案 how to merge 2 queries in this post

答案 1 :(得分:1)

将你的meta_query放在tax_query之后,用' get_meta_sql'包装WP_Query。过滤,然后用OR替换第一个AND,如下所示:

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

然后是filter函数,用OR替换第一个AND:

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

这样更快,并且可以节省您在合并查询的帖子后过滤重复项的时间。