We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18830
    • 161 Posts
    I need a little snippet that checks if the parent of an document is 0. Neither UltimateParent doesn´t seem to fit because it will return the doc´s ID if the parent is 0 nor GetParent (the snippet).

    So I wrote this little piece of code for a snippet.

    $id = $modx->documentIdentifier;
    $topid = $modx->getParent($id,1,'id');
    return $topid;
    


    Unfortunately it doesn´t return anything when it is put to a document of the first level and "Array" when it will be called from a seceond level document. What´s wrong with the snippet?

    Or is there a way to find out if an document is an grandchild in a site structure like this.


    Site root (id 0)
    - Home
    - foo
    - grandchild

    Thank you for any suggestion.
      • 10487 MODX Staff
      • 1,535 Posts
      You could use the $modx->getParentIds() method to count the number of levels that the document is nested, kinda like:
      $parents = array();
      $parents = $modx->getParentIds($modx->documentObject['id']);
      if (count($parents) == 0) {
           // we have a top level document (i.e. parent is Site Root)
      }
      

      I think that would work in your scenario .... wink
        Garry Nutting
        Senior Developer
        MODX, LLC

        Email: [email protected]
        Twitter: @garryn
        Web: modx.com
        • 18830
        • 161 Posts
        Yes, it works, garryn. Thank you.

        While you were writing your post I found the bug in my code. Here is the right version:

        $thisID = $modx->documentIdentifier;
        $topID = $modx->getParent($thisID,1,'id');
        return $topID[id];
        


        This one will returns nothing on a top level document and the ID of the parent of any document on level 2 or deeper.

        Nevertheless: Your solution seems to be more straightforward and versatile, so I’ll use this. Maybe you should turn this into a little snippet.