Custom KirbyTag to access data on an arbitrary page

I understand that, in a custom KirbyTag, $tag->parent() accesses the parent page object, which can be used as a hook to access fields, files, etc.

I am doing a website with a number of running events, each of which has a consistent folder structure. In the course folder for each I have a table in a structure field.

/race1/course/
/race2/course/
/race3/course/
...

I can access this structure field with $tag->parent(), which enables me to spit out the data into an HTML table.

I would also like to be able to access that structure field data from an arbitrary page, not just the $tag->parent() which contains the structure field. Is there a way to access data from an arbitrary page, say /race2/course/example/? Something along the lines of:

$tagparent = $pages->find(
explode('/',$page->id())[0] .'/'. explode('/',$page->id())[1] . '/course'
);

Thanks,

Keith

I found a solution

$depth = $tag->parent()->depth()-3;
// The example page is 3 levels deep

if($depth == 0){
$tagparent = $tag->parent();
}elseif ($depth == 1) {
$tagparent = $tag->parent()->parent();
}elseif ($depth == 2) {
$tagparent = $tag->parent()->parent()->parent();
};


$data = $tagparent->data()->toStructure();

The data can be accessible on any subpage of the parent holding the data.

I think your code could be shortened a bit:

$tagparent = $tag->parent();
if ($tagparent->depth() > 3) {
  $tagparent = $page->parents()->findBy('intendedTemplate', 'course');
}