Return Parent, Unless it IS the parent

I’m trying to build a simple nav menu, but having issues using $page->parent(). Imagine a site, with a directory (page) called fruit. Inside that, I have three pages: apple, orange, banana. I want the same nav on all four pages (fruit, apple, orange, banana).

Obviously the links to apple, orange and banana are easy, and $page->parent() on those pages returns me to fruit. BUT… if I’m on the fruit page, the link to fruit will take me up another directory since ITS parent is “food” (for instance).

Is there a way to return the parent EXCEPT in the case where it is the parent itself?

How do you define “parent” here? As a page with a specific template? Meaning “fruit” has the template category.php and “apple” the template item.php or something like that.

If so, you can check by the template:

$parent = r($page->template() == 'category', $page, $page->parent());

Now we’re getting somewhere! I didn’t occur to me to use different templates for the category and item. I was trying to use a single template for both. I could certainly use your solution, or for that matter, since the “link” to the category page is effectively itself,I could just use <a href="#"> in the template.

Yes, that could work too.

Please note though that “empty” links aren’t that great semantically. Since clicking it does not lead to anywhere, I would prefer a <span> in that case instead of a link. But that’s just a detail.

Absolutely. Not good for Google either! I think the main reason I had my head stuck on a single template, is that other than that one link, everything else in the template is exactly the same. It seems odd to have a whole new template, just for one link.

Well, the idea with the template was just an example. You need some kind of information that tells if the current page is the parent you are looking for or not, it doesn’t matter what it is.

Other alternatives:

  • Use a checkbox field that gets checked for the parent
  • Check if the parent has children with $page->hasChildren() (only works if the “children” don’t have children themselves)

Great stuff! Many thanks, as always.