If you want to auto-create a given set of subpages every time you create a particular page, you can achieve this with a
page.create:after hook. To make it more versatile, you can define a custom blueprint setting that leverages Kirby's new
$page->blueprint() method. We will take you step by step through an example based on the Starterkit.
Let's say every time you create a new
note page (in the Panel or programmatically), you want to create two subpages:
Add the custom option
subpage_builder to the
note.yml blueprint in the Starterkit:
As you can see above, we also added a pages section for the subpages.
Now we need a hook that is called each time a page is created.
We can define it within the
return array of our
Within the hook's callback function, we call a function called
buildPageTree() with the newly created
$page as first parameter. We will define that function in a plugin.
buildPageTree() function is a recursive function that builds new subpages as long as the blueprint has a subpage builder setting with valid values.
In this example, all subpages in the tree are automatically published. That way, they will be published together with the parent without any further interaction.
The workflow we outlined above works with a
page.create:after hook, so when a new page is created. But what if you want to restructure your site and add those subpages after (some) of the pages already exist.
There are several ways to deal with this:
We can call the
buildPageTree() method in a
page.update:after hook to create the subpages when a page is updated.
Depending on whether the page can have other subpages, you might have to adapt the condition.
In many cases, waiting for a page to be updated is not ideal, though.
We can use a
route.after hook to call the
buildPageTree() method when a page is visited rather then updated. This is usually more useful, because you would have to visit a page anyway to access the subpages:
As before, you might have to adapt the condition.
In a plugin, or for one time use even in a template, we can call the
buildPageTree() method on all pages that don't have children yet:
Again, this is only an example and your conditions may be different.