Get page attribute recursively

Submitted by remo - 4 years ago

When you work with attributes, you often want to search for them recursively, think of an attribute where you can specify a background picture. You might want to assign a picture to the home page (the top level page) but still have the ability to override that default picture for a few selected pages. The script shown below will do that for you. It looks for an attribute with the handle "background_picture" on the current page and goes up in the sitemap and only stops if it has either found a picture or the top level page (the home page).

// get background picture from current page. In case there's no picture,
// search for it in the parent page and if there's still no picture, in
// the parent of that and then in the parent of that...

$backgroundPicture = false;

// assign current page, it's where we want to start
$page = $c;

while (!$backgroundPicture && !$backgroundPicture instanceof File) {
    $backgroundPicture = $page->getAttribute('background_picture');
    
    // get parent page if we still haven't found a picture
    if (!$backgroundPicture instanceof File) {
        $page = Page::getByID($page->getCollectionParentID());
        
        // make sure we stop in case there's no parent page to be found
        if (!is_object($page) || $page->isError()) {
            break;
        }
    }
}

// display image attribute in case we've found one
if ($backgroundPicture instanceof File) {
    echo '<img src="' . $backgroundPicture->getURL() . '" alt=""/>';
}
Stats Categories Tags
comments powered by Disqus