WP_Query:过滤tax_query或meta_query

时间:2016-06-10 03:41:15

标签: wordpress

如何组合tax_query和meta_query的结果?

例如: tax_query结果为: Post1,Post2。

和meta_query重新开始: Post3。

我想结合2个查询的结果。 这是我的部分代码:

'tax_query' => array(
     'relation' => 'AND',
     array(
         'taxonomy' => 'tax1',
         'field'    => 'term_id',
         'terms'    => array(1,2,3),
     ),
     array(
         'taxonomy' => 'tax2',
         'field'    => 'term_id',
         'terms'    => array(1,2,3),
     ),
 ),
 'meta_query' => array(
     array(
         'key'     => 'meta1',
         'value'   => '1',
         'compare' => '=',
      ), 
 ),

这里问了同样的问题,但没有回答。所以我重新打开它。 谢谢!

2 个答案:

答案 0 :(得分:2)

听起来你想让它像一个' OR'其中返回与tax_querymeta_query匹配的帖子。

不幸的是,使用WP_Query无法做到这一点。

你需要写一个custom database call,或者只是单独查询它们并对你的PHP结束进行检查(如果你知道你有一个相对的,那就没问题了。少数结果,但要注意,这不一定会扩展到一个巨大的网站。)

答案 1 :(得分:1)

实现这样的查询的唯一方法是使用$wpdb全局和SQL语句为db创建自定义查询。我认为会是这样的:

global $wpdb;
$querystr = 
"
SELECT * FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id)
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy as term_taxonomy1 ON($wpdb->term_relationships.term_taxonomy_id = term_taxonomy1.term_taxonomy_id)
LEFT JOIN $wpdb->term_taxonomy as term_taxonomy2 ON($wpdb->term_relationships.term_taxonomy_id = term_taxonomy2.term_taxonomy_id)
LEFT JOIN $wpdb->terms as tax1_term1 ON(term_taxonomy1.term_id = tax1_term1.term_id)
LEFT JOIN $wpdb->terms as tax1_term2 ON(term_taxonomy1.term_id = tax1_term2.term_id)
LEFT JOIN $wpdb->terms as tax1_term3 ON(term_taxonomy1.term_id = tax1_term3.term_id)
LEFT JOIN $wpdb->terms as tax2_term1 ON(term_taxonomy2.term_id = tax2_term1.term_id)
LEFT JOIN $wpdb->terms as tax2_term2 ON(term_taxonomy2.term_id = tax2_term2.term_id)
LEFT JOIN $wpdb->terms as tax2_term3 ON(term_taxonomy2.term_id = tax2_term3.term_id)
WHERE 
(
    (
        (term_taxonomy1.taxonomy = 'tax1') 
        AND 
        (tax1_term1.term_id = 1 AND tax1_term2.term_id = 2 AND tax1_term3.term_id = 3)
    )
    OR
    (
        (term_taxonomy2.taxonomy = 'tax2') 
        AND 
        (tax2_term1.term_id = 1 AND tax2_term2.term_id = 2 AND tax2_term3.term_id = 3)
    )
)
OR
(
    $wpdb->postmeta.meta_key = 'meta1' AND $wpdb->postmeta.meta_value = '1'
)
ORDER BY $wpdb->postmeta.meta_value ASC
"
$pageposts = $wpdb->get_results($querystr, OBJECT);

然后,您可以使用$pageposts循环迭代WP_Query