2

This one seems deceptively simple, but I am struggling. My home page is a single, and in that template I want to retrieve the children of a specific entry in a structure, then loop through them. Here is a code example that does not work:

{% set entries = craft.entries.id(4).children %}
{% for entry in entries %}
    do something
{% endfor %}

This returns the page with id 4 instead of its children.

I also tried something like:

{% set entries = craft.entries.section('pages').descendantsOf('targetpage') %}

Maybe I need to retrieve the entire section and do a conditional loop for entries where the parent entry ID is 4, but the proper syntax for that eludes me.

Could someone please point me in the right direction? Thanks!

1 Answer 1

3

You need to get the parent entry model before requesting its children with the getChildren method. craft.entries.id(4) only creates a criteria model prepared to query for entries matching your criteria. You now have to use the first method to query for an entry model.

{% set parent = craft.entries.id(4).first() %}

{# Check if it indead returned an entry model, could also return nothing #}
{% if parent %}
    {% set children = parent.children %}
{% endif %}
1
  • Thank you! I tried exactly this but without the .first(). The one thing that still trips me up when working in Craft is remembering that even single results are returned in an array. Commented Jan 29, 2016 at 17:41

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.