Get the Pagetitle of a Resource’s Parent in MODX

A MODX Forum user asked how to get the pagetitle of the current resource’s parent in Revolution. I thought I’d put my answer up here to make it easier to find.

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:

<br />[[!GetParentPagetitle]]<br />

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

<br />$output = ”;<br /><br />/* Get the current resource’s ‘parent’ field */<br />$parentId = $modx-&amp;gt;resource-&amp;gt;get(‘parent’);<br /><br />/* Get the parent object */<br />$parentObj = $modx-&amp;gt;getObject(‘modResource’, $parentId);<br /><br />/* If we have the parent,<br /> get and return the pagetitle */<br /><br />if ($parentObj) {<br /> $output = $parentObj-&amp;gt;get(‘pagetitle’);<br />}<br /><br />return $output;<br /><br />

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:

<br />$parentObj = $modx-&amp;gt;getObject(‘modResource’, $modx-&amp;gt;resource-&amp;gt;get(‘parent’));<br />return $parentObj? $parentObj-&amp;gt;get(‘pagetitle’) : ”;<br />


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray

I am the author of MODX: The Official Guide and over 30 MODX add-on components. I host Bob's Guides, a source of valuable information for MODX users, and I've been very active in the MODX Forums with over 14,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *


8 × = 32

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>