MODX Quick Tip: Get ID of Grandparent

Jul 30, 2012

The Problem

You need to get the ID of the MODX Resource that is the grandparent of the current document. Not the [[*parent]], not the "UltimateParent", but the grandparent. This exact question was asked in the MODX Support channel recently, and long-time MODX All-Star Developer Garry Nutting responded with this little snippet:

$id = $modx->resource->get('id');   
$parents = $modx->getParentIds($id, 2);   
$grandParent = $parents[1];    
return $grandParent;

Break it down:

This snippet gets the current document's ID and traverses up through its parents in the Context cache to find the "grandparent". It then outputs the grandparent ID. Super simple, super useful, super easy. Just copy and paste that code into a new Snippet, name it whatever you want (I used "GrandParent") and then call it from any page or template: [[GrandParent]].

That's it. Have fun!