How to make simple setting for editor to redirect parent to it's first child page?

Hi, I can make redirect with php or in .htaccess of course, but would like to let editor have control over it.

What I need:

So that instead of seeing parent page, user would go to first child.

I would like to have toggle setting in panel in parent page:
(1) show by default, like now
(2) redirect to first child

I know how to do setting itself, just a filed in blueprint, but can you guide me how to make this kind of redirect?

Maybe it could even better be “replacement” of parent link, so that parent would show first child. To avoid redirection. But it would probably need more programming?

You could have a redirect toggle field in your blueprint, then in your page’s controller:

// site/controllers/page.php

<?php 

return function($page) {
    // check if the visitor should be redirected
    $redirect = $page->redirect()->isTrue();
    // get your listed children collection
    $children = $page->children()->listed();

    // only redirect if $redirect is true and there's at least one listed child
    if($redirect && $children->count()) {
        go($children->first());
    }
};

edit: logic would be the same to echo the link of the child instead of its parent, something like:


$url = $redirect && $children->count() ? $children->first()->url() : $page->url();
echo $url; 

Thank you! If I already have some rules in that template controller, where should new code go? Now I have:

<?php
return function($kirby, $page) {

    if ($kirby->request()->is('POST') && get('submit')) {
..etc..

Ah, sorry, it’s actually different template :slight_smile: still would be good to know :slight_smile:

If you want to completely skip the parent page and all its logic, before your existing code. Else, it depends of what your existing code does.

It’s checking and sending webform http://metalista.lt.grikis.serveriai.lt

In such a case if you want to redirect only after successfully sending the form, place the code where you check for the success of whatever you’re doing with the form data.

1 Like

That seem to be a different template? Or are they all using the same template/controller

Tried your first solution, works perfect, thank you!