一、WordPress排除某分类所有循环文章
在WordPress中,如果你想要排除某个分类下的所有文章,你可以使用query_posts
函数来修改查询,排除特定的分类。以下是一个简单的代码示例,展示了如何在循环中排除特定分类ID为3的所有文章。
<?php
$excluded_category = 3; // 设置你想要排除的分类ID
$args = array(
'cat' => -$excluded_category, // 排除特定分类ID
);
query_posts($args);
if (have_posts()) :
while (have_posts()) : the_post();
// 你的文章内容代码
get_template_part('template-parts/content', get_post_format());
endwhile;
else :
// 如果没有文章显示的代码
get_template_part('template-parts/content', 'none');
endif;
wp_reset_query(); // 重置查询
?>
在这个例子中,query_posts
函数被用来修改查询,通过设置'cat' => -$excluded_category
排除特定的分类。wp_reset_query()
函数在循环结束后被调用,以确保后续的查询不会受到影响。
请注意,query_posts
和wp_reset_query()
应该小心使用,因为它们可能会影响到WordPress的全局查询,所以在循环结束后使用wp_reset_query()
是一个好习惯。
二、WordPress排除某些分类所有循环文章
<?php
// 假设你要排除的分类ID是 123 和 456
$excluded_category_ids = array(370, 456);
// 主循环,用于获取文章
if (have_posts()) :
while (have_posts()) : the_post();
// 检查当前文章是否属于排除的分类
if (has_term($excluded_category_ids, 'category', get_the_ID())) {
// 如果属于排除分类,跳过当前文章
continue;
}
// 输出你想要的内容,例如文章标题
the_title();
endwhile;
endif;
?>
三、下面是我改的代码
<?php
// WordPress排除某些分类所有循环文章
// 假设你要排除的分类ID是 1 和 370
$excluded_category_ids = array(1, 370);
// 主循环,用于获取文章
if (have_posts()) :
while (have_posts()) : the_post();
// 检查当前文章是否属于排除的分类
if (has_term($excluded_category_ids, 'category', get_the_ID())) {
// 如果属于排除分类,跳过当前文章
continue;
}
// 输出你想要的内容,例如文章标题
the_title();
// 你的文章内容代码
get_template_part('template-parts/content', get_post_format());
endwhile;
endif;
?>