Custom Snippet: get parent of resource with specific ID

I’m writing a custom snippet and I need to get the pagetitle of the parent resource from the ID which is stored in $resource.

I only found how to get the parent of the current resource but not how to make it use my variable $resource and find the parent of that:

$parent = $modx->resource->getOne('Parent');
return $parent->get('pagetitle');

I’m new to creating custom snippets but I hope there is a simple solution to this.

The goal of the snippet is to get the pagetitle from the parent of the current resource?

there is a snippet called ultimate parent that could do that
but if you like to create your own then you are almost there I think, maybe its better to rename $resource to $resourceId, for clarity.

$myResource = $modx->getObject('modResource', $resourceId);
$parent = $modx->getObject('modResource', $myresource->get('parent'));
$pagetitle = $parent->get('pagetitle');

https://docs.modx.com/3.x/en/extending-modx/xpdo/class-reference/xpdo/xpdo.getobject

No, there’s more to it, that was just the part that I’m stuck with. Thank you for the help and hints on clarifying my code!

Here is a slightly faster method (using dimmy’s renamed variable):

    $query = $modx->newQuery('modResource', array (
        'id' => $resourceId,
    ));
    $query->select('pagetitle');
    $parentPagetitle = $modx->getValue($query->prepare());
1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.