You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CraftCMS多分类条目循环遍历如何实现同一条目不重复展示

CraftCMS 跨分类关联条目去重实现方案

核心思路是维护一个全局的已渲染条目ID数组,每次查询当前分类下的关联文章时,直接排除已经渲染过的条目ID;当前分类下的文章渲染完成后,将这批文章的ID追加到已渲染数组中,从查询源头避免重复条目出现,比在渲染循环里做重复判断性能更好。

修改后可直接使用的代码

{% set selectedCategories = craft.categories()
  .id([12605, 12619])
  .all()
%}

{% set articleAuthor = entry.id %}
{# 初始化已渲染条目ID集合,用于跨分类去重 #}
{% set renderedArticleIds = [] %}

{% for category in selectedCategories %}
  {% set articlesQuery = craft.entries()
    .section('articles')
    .relatedTo([
      'and', {articleAuthor}, {category}
    ]) %}

  {# 存在已渲染条目时,查询阶段直接排除对应ID #}
  {% if renderedArticleIds | length %}
    {% do articlesQuery.id(['not'] | merge(renderedArticleIds)) %}
  {% endif %}

  {% set articles = articlesQuery.all() %}

  {% if articles %}
    {# 分类标题等区块头部内容可放在这里 #}
    <div class="category-block">
      <h3>{{ category.title }}</h3>
      {% for article in articles %}
        {# 原有条目渲染逻辑保留在这里即可 #}
        <div class="article-card">
          <a href="{{ article.url }}">{{ article.title }}</a>
        </div>
      {% endfor %}
    </div>

    {# 将当前分类已渲染的文章ID追加到去重集合 #}
    {% set renderedArticleIds = renderedArticleIds | merge(articles | column('id')) %}
  {% endif %}
{% endfor %}

关键逻辑说明

  • 初始状态下renderedArticleIds为空数组,不会影响第一个分类的正常查询结果
  • 排除逻辑加在数据库查询层,不需要在二层文章循环里重复判断条目是否已输出,文章量级较大时性能优势明显
  • 分类遍历顺序完全和原有配置一致,条目只会出现在遍历顺序中第一个匹配到的分类区块下,不会跨区块重复
  • 原有分类筛选、作者关联的查询逻辑完全保留,仅新增了去重相关的代码,侵入性极低

内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 10:39:15