1

The following outputs all sections and their entry types, but I'm struggling to work out how I output only the entry types from the "blog" section.

{% for section in craft.app.sections.allSections() %}
  <h2>{{ section.name }}</h2>

  <ul>
    {% for type in section.getEntryTypes() %}
      <li>{{ type.name }}</li>
    {% endfor %}
  </ul>
{% endfor %}

I thought this would work

{% for type in craft.entries.section('blog').getEntryTypes() %}
  <p>{{ type.name }}</li>
{% endfor %}

But I've hit a wall because getEntryTypes() is an unknown method.

2 Answers 2

3

You're close – this should work in Craft 3.x and 4.x (look at @obs answer for Craft 5):

{% set blogSection = craft.app.sections.getSectionByHandle('blog') %}
{% set blogSectionEntryTypes = blogSection.getEntryTypes() %}

{% for entryType in blogSectionEntryTypes %}
    <p>{{ entryType.name }}</p>
{% endfor %}

The reason why craft.entries.section('blog').getEntryTypes() didn't work is that craft.entries will actually create an ElementQuery, which is used to query for elements (e.g. entries).

When you use craft.app.sections or craft.app.getSections() (it doesn't really matter which variant you use, although the latter is a micro-optimisation in terms of performance) you're interacting with the Sections service, which is what you need to use to work with sections and their entry types directly, rather than entries.

2
  • 1
    Thank you very much for the solution and for the explanation! I'll read up some more on how Craft works, particularly the parts you've mentioned. Oct 2, 2018 at 12:50
  • How can the resulting list of entry types be sorted? I'm having no luck in Craft 4 using the |sort filter on these things.
    – Sandwich
    Sep 10, 2023 at 12:37
1

For anyone coming here and looking for a solution for Craft 5:

It now works like that:

{% set section = craft.app.entries.getSectionByHandle('blog') %}
{% set entryTypes = craft.app.entries.getEntryTypesBySectionId( section.id ) %}

Here are the docs: https://docs.craftcms.com/api/v5/craft-services-entries.html#entries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.