From 9add4e5f8203f9bdcb6b498041a872c090f5ff98 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 29 May 2020 14:14:30 -0400 Subject: [PATCH] Add support for $page->parents(true); which returns parents in reverse order (closest to furthest) rather than breadcrumb order. --- wire/core/Page.php | 10 ++++++++-- wire/core/PageTraversal.php | 7 ++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/wire/core/Page.php b/wire/core/Page.php index f0e9ed3b..a20c7b1e 100644 --- a/wire/core/Page.php +++ b/wire/core/Page.php @@ -2409,7 +2409,9 @@ class Page extends WireData implements \Countable, WireMatchable { * Return this page’s parent pages, or the parent pages matching the given selector. * * This method returns all parents of this page, in order. If a selector is specified, they - * will be filtered by the selector. + * will be filtered by the selector. By default, parents are returned in breadcrumb order. + * In 3.0.158+ if you specify boolean true for selector argument, then it will return parents + * in reverse order (closest to furthest). * * ~~~~~ * // Render breadcrumbs @@ -2421,11 +2423,15 @@ class Page extends WireData implements \Countable, WireMatchable { * // Return all parents, excluding the homepage * $parents = $page->parents("template!=home"); * ~~~~~ + * ~~~~~ + * // Return parents in reverse order (closest to furthest, 3.0.158+) + * $parents = $page->parents(true); + * ~~~~~ * * #pw-group-common * #pw-group-traversal * - * @param string|array $selector Optional selector string to filter parents by. + * @param string|array|bool $selector Optional selector string to filter parents by or boolean true for reverse order * @return PageArray All parent pages, or those matching the given selector. * */ diff --git a/wire/core/PageTraversal.php b/wire/core/PageTraversal.php index 8c22f638..a6dfe982 100644 --- a/wire/core/PageTraversal.php +++ b/wire/core/PageTraversal.php @@ -160,18 +160,19 @@ class PageTraversal { * Return this page's parent pages, or the parent pages matching the given selector. * * @param Page $page - * @param string|array $selector Optional selector string to filter parents by + * @param string|array|bool $selector Optional selector string to filter parents by or boolean true for reverse order * @return PageArray * */ public function parents(Page $page, $selector = '') { $parents = $page->wire('pages')->newPageArray(); $parent = $page->parent(); + $method = $selector === true ? 'add' : 'prepend'; while($parent && $parent->id) { - $parents->prepend($parent); + $parents->$method($parent); $parent = $parent->parent(); } - return strlen($selector) ? $parents->filter($selector) : $parents; + return !is_bool($selector) && strlen($selector) ? $parents->filter($selector) : $parents; } /**