Excluding Categories

拟墨画扇 提交于 2019-12-24 08:22:56

问题


Currently I'm listing all post categories but I'm hoping to exclude certain categories that exist e.g. Uncategorised.

This is how I'm initiating categories at the moment:

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

and listing the categories via

{% for cat in categories %}

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

{% endfor %}

回答1:


You have several possibilities. Here are two:

1. Exclude in Query

When using Timber::get_terms() or Timber::get_posts() you can use the same arguments that you would use with the get_terms() function of WordPress.

The exclude parameter expects the term IDs that you want to exclude. Uncategorized normally has the ID 1.

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

2. Exclude in Twig

Twig allows to you to add a condition to the for loop to exclude items that you want to ignore in the loop.

This way, you can e.g. check for the slug to not be "uncategorized", but you could also check the ID with category.id != 1.

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



回答2:


If you know the name of the categories which you don't want to include then you can use not in with the following code.

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

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


来源:https://stackoverflow.com/questions/39584142/excluding-categories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!