排除类别

Excluding Categories

目前我列出了所有 post 类别,但我希望排除某些存在的类别,例如未分类。

这就是我目前启动类别的方式:

$context['categories'] = Timber::get_terms('category');

并通过

列出类别
{% for cat in categories %}

<li><a style="margin: 0;" href="{{cat.link}}">{{cat.name}}</a></li>

{% endfor %}

你有几种可能性。这里有两个:

1。在查询中排除

使用 Timber::get_terms()Timber::get_posts() 时,您可以使用与 WordPress get_terms() function 相同的参数。

exclude 参数需要您要排除的术语 ID。未分类的通常 ID 为 1。

$context['categories'] = Timber::get_terms( 'category', array(
    'exclude' => 1
) );

2。在 Twig 中排除

Twig 允许您add a condition to the for loop排除您想要在循环中忽略的项目。

这样,您可以检查 slug 是否为 "uncategorized",但您也可以使用 category.id != 1.

检查 ID
{% for cat in categories if category.slug != 'uncategorized' %}
    <li><a href="{{ cat.link }}">{{ cat.name }}</a></li>
{% endfor %}

如果您知道不想包含的类别名称,则可以使用 not in 和以下代码。

{% set categorisedValues = ['one','two','three','four','five'] %}
{% set uncategorisedValues = ['one','two'] %}

{% for categorised in categorisedValues %}
    {% if categorised not in uncategorisedValues %}
        {{ categorised  }}
    {% endif %}
{% endfor %}