Blog

Code Examples for Statamic Navigation Structures

Statamic

Navigation structures in Statamic offer the ability to construct complex page trees with pages and subpages. The following code examples will assist in maintaining and creating these structures.

Reset Structure

To reset the entire structure of a page, the following code can be used:

use Statamic\Facades\Collection;

$structure = Collection::findByHandle("pages")->structure();
$tree = $structure->in("de");
$tree->delete();

This code would reset the structure of the de multisite.

Copy/Synchronize Structure

Consider the following scenario: I have a multisite website with a German and an English version. Both the German and the English versions contain the same pages, linked together via origin. The following code copies the structure of the German pages, i.e., the German page tree, to the English pages or the English page tree:

use Statamic\Facades\Collection;

$structure = Collection::findByHandle("pages")->structure();
$sourceTree = $structure->in("de");
$targetTree = $structure->in("en");
$targetTree->delete();

$dePages = $sourceTree->flattenedPages();

foreach ($dePages as $dePage) {
    // If no translation is found => Skip
    if (!$dePage->in("en")) {
        continue;
    }

    if ($dePage->parent() && !$dePage->parent()->isRoot()) {
        $targetTree->appendTo($dePage->parent()->in("en")->id, $dePage->in("en"));
    } else {
        $targetTree->append($dePage->in("en"));
    }
}

$targetTree->save();