I've set up a channel using categories to distinguish between different blog post types. The majority will probably be in one category, so it would be great to be able to specify a default category. However, as far as I can see the Category field type (unlike, say, the Drop Down field type) doesn't give you the option to set a default... Is there any way of doing this?
2 Answers
You could output the categories in a way that makes them look like they are from a specific category when they don't have any categories assigned to them.
When you're outputting any of the entries, just add a custom link if there isn't a category assigned:
{% if entry.categories|length %}
{% for category in entry.categories %}
<a href="/blog/category/{{ category.url }}">{{ category.title }}</a>
{% endfor %}
{% else %}
<a href="/blog/category/default-category-slug">Default Category Title</a>
{% endif %}
Create a route that points "/blog/category/default-category-slug" to your filtered listing template (/blog/index, /blog/category etc.).
On the filtered listing template check if the default category slug is in the URL:
{% if craft.request.getSegment(3) == 'default-category-slug' %}
If that evaluates to true, you can now get the entries without any categories assigned to them and loop through them, see this question: How to find entries with no category:
{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}
{% for entry in uncategorized %}
{# show entry #}
{% endfor %}
Any other times you need to get the entries that "have" the default category, to loop through them, use .relatedTo on etc., instead of using:
{% set entriesWithDefaultCategory = craft.entries.section('blog').relatedTo('the-default-category') %}
Use this like on the filtered listing above:
{% set uncategorized = craft.entries.section('blog').search('-categories:*') %}
- 3,015
- 1
- 18
- 33
Not with the out-of-the-box field types. You could create a field type that is category+default. The Default Color plugin might be a good place to start.
- 12,047
- 22
- 55