WordPress:如何在single-teams.php中仅展示当前文章关联分类的文章?
解决方案
你的问题核心是category__in参数写死了固定分类ID(array(2)),导致无论当前打开哪个团队页面,都会拉取同一分类的文章。要实现“仅展示当前团队关联分类的新闻”,需要动态获取当前single-teams文章关联的分类ID,再传入get_posts的查询参数中。
修改后的完整代码
// 获取当前single-teams文章关联的分类ID数组 $current_team_cats = get_the_category(get_the_ID()); $category_ids = wp_list_pluck($current_team_cats, 'term_id'); // 仅当有分类关联时执行查询 if (!empty($category_ids)) { $args = array( 'posts_per_page' => 4, 'offset' => 0, 'orderby' => 'date', 'order' => 'DESC', 'category__in' => $category_ids, // 替换为动态获取的分类ID 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true, ); $news = get_posts($args); foreach ($news as $post) : setup_postdata($post); $image = get_field('image', $post->ID); $image = $image['sizes']['large']; $catNames = array(); foreach(get_the_category() as $category) { $catNames[] = $category->cat_name; } // 此处补充你的文章内容输出逻辑(如标题、链接等) endforeach; wp_reset_postdata(); // 重置全局post变量,避免后续查询出错 }
关键细节说明
get_the_category(get_the_ID()):获取当前single-teams文章关联的所有分类对象wp_list_pluck($current_team_cats, 'term_id'):从分类对象数组中提取纯ID,生成符合category__in要求的ID数组!empty($category_ids)判断:避免当前文章未关联任何分类时,触发无效查询wp_reset_postdata():必须添加,防止全局$post变量被循环修改后影响后续模板逻辑
如果你的single-teams自定义文章类型使用的是自定义分类法(而非默认的category),只需替换分类获取逻辑:
// 假设自定义分类法的slug为"team_category" $current_team_cats = get_the_terms(get_the_ID(), 'team_category'); $category_ids = wp_list_pluck($current_team_cats, 'term_id');
内容的提问来源于stack exchange,提问作者regga
相关产品推荐
相关产品推荐

