1

I'm experimenting with using Craft in a headless way and am successfully using the Element API to return all the data required to show individual pages.

However, to be able to show sub navigation and where a particular page fits into my site's 'structure' hierachy, I'd like to pull out the entire page hierarchy and then use that info in my application.

Does anyone know how to go about that using the Element API?

Thanks in advance for any clues.

Cheers,

Jim

1

It's not the most economical way to do it but if you don't have hundreds and hundreds of entries, this should do it for you:

<?php
use craft\elements\Entry;

function getChildren($entries){
    foreach ($entries as $entry) {
        $items[] = [
            'title' => $entry->title,
            'slug' => $entry->slug,
            'level' => $entry->level,
            'children' => $entry->hasDescendants ? getChildren($entry->children) : false
        ];
    }
    return $items;
}

return [
    'endpoints' => [
        'structure.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => [
                    'section' => 'structure',
                    'orderBy' => 'lft asc',
                    'level' => 1,
                    'limit' => null
                ],
                'transformer' => function(Entry $entry) {
                    return [
                        'title' => $entry->title,
                        'slug' => $entry->slug,
                        'level' => $entry->level,
                        'children' => $entry->hasDescendants ? getChildren($entry->children) : false
                    ];
                },
            ];
        }
    ]
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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