具有多个 ACF 分类法的 Wp_Query - 类别和标签

问题描述

我创建了一个后过滤器显示管理员可以在其中转到页面添加 ACF 块并选择哪些类别和标签,这将决定哪些帖子将显示在前端。当仅选择类别和仅选择标签时,一切正常。但是当同时选择类别和标签时,没有显示并且显示所有帖子(如果没有选择任何内容,这就是我想要发生的事情。)。我的代码低于任何帮助都会很棒。如果您需要更多信息,请告诉我。谢谢。

    $categories = get_field( 'category',false,true );
if ( $categories ) {
if ( ! is_array( $categories ) ) {
$categories = array( $categories );
}
$categories = array_map( 'intval',$categories );
}

// get the ID values of the terms and not term objects.
$tags = get_field( 'tags',true );
if ( $tags ) {
if ( ! is_array( $tags ) ) {
$tags = array( $tags );
}
$tags = array_map( 'intval',$tags );
}

$uncat = get_cat_id( 'Uncategorized' );
$excat = get_cat_id( 'Exclude' );
$excatall = get_cat_id( 'Exclude All' );

if ( ! empty( $categories ) && ! empty( $tags ) ) {
$args = array(
'post_type' => 'post','post_status' => 'publish','posts_per_page' => -1,'order' => ASC,'orderby' => 'date','tax_query' => array( // PHPcs:ignore
'relation' => 'OR',array (
'relation' => 'AND',array(
'taxonomy' => 'category','category__not_in' => array( $uncat,$excat,$excatall ),),array (
'taxonomy' => 'post_tag','terms' => $tags,'operator' => 'IN','terms' => $categories,);
} elseif ( ! empty( $tags ) && empty( $categories ) ) {
$args = array(
'post_type' => 'post','tax_query' => array( // PHPcs:ignore
array(
'taxonomy' => 'post_tag',);
} elseif ( ! empty( $categories ) && empty( $tags ) ) {
$args = array(
'post_type' => 'post','tax_query' => array( // PHPcs:ignore
array(
'taxonomy' => 'category',);
} else {
$args = array(
'post_type' => 'post',);
}

解决方法

通过在第一部分中添加它来让一切正常工作。

$tax_query[] = array(
        'relation' => 'OR',array(
            'taxonomy' => 'category','field'    => 'term_id','terms'    => $categories,),array(
            'taxonomy' => 'post_tag','terms'    => $tags,);

    $args = array(
        'post_type'        => 'post','post_status'      => 'publish','posts_per_page'   => -1,'order'            => ASC,'orderby'          => 'date','category__not_in' => array( 10,11,12 ),'tax_query'        => $tax_query,// phpcs:ignore
    );