如何在WordPress中通过查询参数按ID排除分类文章
如何在分类查询中排除指定文章?
要实现从分类查询里排除指定文章,你只需要修改查询参数中的post__not_in数组,把要排除的文章ID添加进去即可——这个参数本身就是WordPress用来指定需要排除的文章ID集合的。
具体修改方式:
- 固定排除特定文章:直接在原有的
post__not_in数组里追加要排除的文章ID。比如你要排除ID为123和456的文章,修改后的代码片段如下:
// Query args. $args = array( 'posts_per_page' => apply_filters( 'my_theme_related_blog_posts_count', absint( get_theme_mod( 'my_theme_blog_related_count', '3' ) ) ), 'orderby' => 'DESC', // 追加要排除的文章ID到数组 'post__not_in' => array( get_the_ID(), 123, 456 ), 'no_found_rows' => true, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-quote', 'post-format-link' ), 'operator' => 'NOT IN', ), ), ); // If category. if ( 'category' === $term_tax ) { $args['category__in'] = $terms_ids; }
- 动态排除文章(比如从主题设置获取):如果需要通过主题后台配置来管理要排除的文章,可以先获取配置的ID集合,再合并到
post__not_in数组中:
// 从主题设置读取要排除的文章ID(假设设置项为my_theme_excluded_posts,存储逗号分隔的ID字符串) $excluded_ids_str = get_theme_mod( 'my_theme_excluded_posts', '' ); $excluded_post_ids = !empty($excluded_ids_str) ? array_map('absint', explode(',', $excluded_ids_str)) : array(); // Query args. $args = array( 'posts_per_page' => apply_filters( 'my_theme_related_blog_posts_count', absint( get_theme_mod( 'my_theme_blog_related_count', '3' ) ) ), 'orderby' => 'DESC', // 合并当前文章ID和要排除的文章ID 'post__not_in' => array_merge(array(get_the_ID()), $excluded_post_ids), 'no_found_rows' => true, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-quote', 'post-format-link' ), 'operator' => 'NOT IN', ), ), ); // If category. if ( 'category' === $term_tax ) { $args['category__in'] = $terms_ids; }
内容的提问来源于stack exchange,提问作者Wanderlust Consulting
相关产品推荐
相关产品推荐

