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 %}
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 %}
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 %}