我正在尝试按类别显示相关帖子,但是我想排除特定类别,但是它不起作用,我也不知道该如何解决。
<?php
$terms = get_the_terms( $post->ID, 'category' );
if ( empty( $terms ) ) {
$terms = array();
}
$term_list = wp_list_pluck( $terms, 'slug' );
$related_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'post_status' => 'publish',
'post__not_in' => array( $post->ID ),
'orderby' => 'rand',
'exclude' => 9,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term_list
)
)
);
$my_query = new WP_Query($related_args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) :
$my_query->the_post();
the_title();
echo "<br>";
endwhile;
}
wp_reset_query();
?>
答案 0 :(得分:1)
在要排除的猫ID上使用减号(-)
$related_args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'post_status' => 'publish',
'post__not_in' => array( $post->ID ),
'orderby' => 'rand',
'cat' => '-9'
);
检查此链接: https://codex.wordpress.org/Class_Reference/WP_Query
查找:排除属于类别的帖子
答案 1 :(得分:0)
让我们假设您要排除类别ID 9,然后在您的$related_args
中添加以下税收查询-
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => $term_list,
),
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => array( 9 ),
'operator' => 'NOT IN',
),
),
答案 2 :(得分:0)
在category.php页面中,只需将这段代码放在循环之前
<?php
if ( have_post() ) {
if (is_category()){
$category = get_category(get_query_var('cat'));
$child_cats = array();
$child_cats = get_term_children($category, 'category');
query_posts(array('category__not_in' => $child_cats);
}
}
while (have_posts()) : the_post(); $postcount++; ?>