2

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 Answer 1

2

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
                    ];
                },
            ];
        }
    ]
];

1
  • Oli - you're a legend! Thank you so much for helping with this. Apologies for not getting back to you sooner. Commented Nov 27, 2019 at 9:12

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.