Get root page of child

Is there a simple way to get the root page of a child?

about
  contact
    design
    marketing
  information

Maybe something like this:

$page->rootParent('design')->children();

It would first go to about and then give me an object with the children contact and information.

The depth is unknown so I can’t just go 2 steps back or so.

Ideas?

UPDATE

I made it work, kind of. I probably need a recursive function or something if there are not simpler solution. As you can see I hang on a new parent on every new if statement.

<?php if( $p->depth() == 1 && $p->hasChildren() ) : ?>
   <?php pattern('site/main/sidebar/children', ['p' => $p->children() ]); ?>
 <?php elseif( $p->depth() == 2 && $p->parent()->hasChildren() ) : ?>
   <?php pattern('site/main/sidebar/children', ['p' => $p->parent()->children() ]); ?>
 <?php elseif( $p->depth() == 3 && $p->parent()->parent()->hasChildren() ) : ?>
   <?php pattern('site/main/sidebar/children', ['p' => $p->parent()->parent()->children() ]); ?>
<?php endif; ?>

If I give it some time I will get it to work with a recursive function but what I’m really asking for is a more simple way to do it.

Should work with something like $page->parents()->last()->children() maybe? Can’t test what parents() is returning, so can’t say if it has the right functionality…

See https://getkirby.com/docs/cheatsheet/page/parents

The parents() and last() methods work well for this, but won’t work if the current page is a top-level page. You can extend the default page model with the following:

public function rootParent() {
  if(!$this->parent())
    return $this;

  return $this->parents()->last();
}

That should get you the top-level page in most scenarios.

2 Likes

last it is. Thank you :wink:

Thank you both! You have been really helpful. I adapted your code to my needs and this is what I ended up with:

$p = ( $p->depth() == 1 ) ? $p : $p->parents()->last();
pattern('site/main/sidebar/children', ['p' => $p->children() ]);

$p is the same as $page for me. Works great and very short and sweet.

For someone else who read this maybe this code make more sense:

$p = ( $p->depth() == 1 ) ? $p : $p->parents()->last();
print_r( $p->children()->toArray() );

4 posts were split to a new topic: Where to put page model code?