Get the Parent Page Title

How to retrieve and display the page title of the current Resource’s parent.

By Bob Ray
February 10, 2022
Get the Parent Page Title

Here’s quick and easy method for getting the pagetitle of the current Resource’s parent in Revolution.

It can be done with a very simple Snippet that gets the parent field of the current Resource, retrieves its parent object from the database, and gets the content of the parent’s pagetitle field.

This tag goes where you want the parent’s pagetitle to appear:

[[!GetParentPagetitle]]

Here’s the code of the GetParentPagetitle Snippet. It’s a somewhat verbose version to make it easier to understand:

$output = '';

/* Get the current resource's 'parent' field */
$parentId = $modx->resource->get('parent');

/* Get the parent object */
$parentObj = $modx->getObject('modResource', $parentId);

/* If we have the parent,
   get and return the pagetitle */

if ($parentObj) {
    $output = $parentObj->get('pagetitle');
}

return $output;

The if ($parentObj) sanity test is important. Resources at the root of the tree have no parent, so if this Snippet executes in one of them you’ll get a PHP error when $parentObj->get() is called because the $parentObj will be null. Because we set $output to an empty string at the top of the Snippet, that’s what will be returned if there’s no parent.

Here’s a much more compact version of the same Snippet:

$parentObj = $modx->getObject('modResource', $modx->resource->get('parent'));
return $parentObj? $parentObj->get('pagetitle') : '';

And here is a faster version:

$output = '';
$parent = $modx->resource->get('parent')
if ($parent) {
    $query = $modx->newQuery('modResource', $parent);
    $query->select('pagetitle');
    $output = $modx->getValue($query->prepare());
}
return $output;

Bob Ray is the author of the MODX: The Official Guide and dozens of MODX Extras including QuickEmail, NewsPublisher, SiteCheck, GoRevo, Personalize, EZfaq, MyComponent and many more. His website is Bob’s Guides. It not only includes a plethora of MODX tutorials but there are some really great bread recipes there, as well.