I had a problem with this snippet, where if you specify a top which is not in the ancestry of the id, it gets stuck in an infinite loop which isn’t good for the server!
I’ve modified the snippet so it can take an extra parameter (topNotFound) for the ID to return if the page specified is not found before it reaches the root. If this isn’t specified, and the top is not found, it just returns the ID of the current document.
What’s the best way of requesting this is added to the distribution?
<?php
// UltimateParent - snippet for MODx 0.9x
// v1.3
// Travels up the document tree from the current document
// to return the "ultimate" parent
// March 2006 - [email protected]
// Bug fix Sept 17, 2006 - Jason Coward <[email protected]>
// Bug fix Dec 7, 2006 - Nick
// Released to the Public Domain, use as you like
// arguments:
// &id - the id of the document whose parent you want to find
// &top - the top of the search
// &topNotFound - the id to return if the top specified is not found (defaults to current ID)
// examples:
// [[UltimateParent? &id=`45` &top=`6`]]
// will find the first parent of document #45 under document #6
// if id == 0 or top == id, will return id.
// you can use this as the startDoc for DropMenu to create specific submenus.
$top = isset($top)?$top:0;
$id = isset($id)?$id:$modx->documentIdentifier;
$topNotFound = isset($topNotFound )?$topNotFound :$id;
if($id==$top || $id==0) { return $id; }
$pid = $modx->getParent($id,1,'id');
if($pid['id'] == $top) { return $id; }
while ($pid['id'] != $top ) {
$id = $pid['id'];
$pid = $modx->getParent($id,1,'id');
if($pid['id'] == $top) { return $id; }
if($pid['id'] == 0) { return $topNotFound ; }
}
return 0; // if all else fails
?>