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

问题描述 投票:0回答:1

我创建了一个后置过滤器显示,管理员可以在其中添加 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', false, 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',
),
),
array(
'taxonomy' => 'category',
'terms' => $categories,
'operator' => 'IN',
),
),
);
} elseif ( ! empty( $tags ) && empty( $categories ) ) {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => ASC,
'orderby' => 'date',
'category__not_in' => array( $uncat, $excat, $excatall ),
'tax_query' => array( // phpcs:ignore
array(
'taxonomy' => 'post_tag',
'terms' => $tags,
),
),
);
} elseif ( ! empty( $categories ) && empty( $tags ) ) {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => ASC,
'orderby' => 'date',
'category__not_in' => array( $uncat, $excat, $excatall ),
'tax_query' => array( // phpcs:ignore
array(
'taxonomy' => 'category',
'terms' => $categories,
),
),
);
} else {
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => ASC,
'orderby' => 'date',
'category__not_in' => array( $uncat, $excat, $excatall ),
);
}
php wordpress categories taxonomy acfpro
1个回答
0
投票

在第一部分中添加此内容即可让一切正常工作。

$tax_query[] = array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => $categories,
        ),
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'term_id',
            '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
    );
© www.soinside.com 2019 - 2024. All rights reserved.