問題描述

我想使用 WP_Query()類來過濾我的一些帖子。我現在面臨的問題是處理分類法查詢。通常,WP_Query()只處理 tax_query()(AND 或 OR) 的一個關係,但是我需要的是在 tax_query()上混合使用這些關係,可以如何實現?例如

'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'taxonomy1',
            'field' => 'slug',
            'terms' => array( $term)
        ),
        array(
            'taxonomy' => 'taxonomy3',
            'field' => 'slug',
            'terms' => 'terms' => array( $term3),
            'operator' => 'IN',
        )
       // below i want to use OR relationship
       'relation' => 'OR',
      array(
            'taxonomy' => 'taxonomy4',
            'field' => 'slug',
            'terms' => array( $term4)
        ),
        array(
            'taxonomy' => 'taxonomy2',
            'field' => 'slug',
            'terms' => 'terms' => array( $term2),
            'operator' => 'IN',
        )
    )  

我知道上面的程式碼不行,我需要用 WP_Query()過濾器來做嗎?任何想法?

最佳解決方案

這可以透過使用 term_taxonomy_id 而不是 slug 來完成,這將有效地忽略指定的分類法,只需檢視唯一的 term_taxonomy_id 欄位。這將使您能夠有效地進行混合關係。您需要使用 AND 的整體關係,並使用 IN 運運算元將所有與 OR 相關的術語放在一個專案中。您將需要首先將所需的術語對映到其 term_taxonomy_ids 。

$taxes = array( 'taxonomy1', 'taxonomy2', 'taxonomy3', 'taxonomy4' );

foreach ( $taxes as $tax ) {
    $terms = get_terms( $tax );

    foreach ( $terms as $term )
        $tax_map[$tax][$term->slug] = $term->term_taxonomy_id;
}


$args['tax_query'] => array(
    'relation' => 'AND',
    array(
        'taxonomy' => 'taxonomy1',
        'field' => 'term_taxonomy_id',
        'terms' => array( $tax_map['taxonomy1'][$slug] )
        'operator' => 'IN',
    ),
    array(
        'taxonomy' => 'taxonomy3',
        'field' => 'term_taxonomy_id',
        'terms' => array( $tax_map['taxonomy3'][$slug] ),
        'operator' => 'IN',
    ),
    array(
        'taxonomy' => 'taxonomy4', // gets ignored
        'field' => 'term_taxonomy_id',
        'terms' => array( $tax_map['taxonomy4'][$slug], $tax_map['taxonomy2'][$slug] ),
        'operator' => 'IN',
    ),
);

請注意,在 3.5 之前,您還需要指定'include_children' => false 。檢視此 Trac 機票瞭解更多:https://core.trac.wordpress.org/ticket/21228

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。