Allow pages to be sorted by arbitrary meta values
This basically works like Pico's `sort_by` Twig filter
This commit is contained in:
parent
b626782b87
commit
414f5ac18e
2 changed files with 28 additions and 3 deletions
|
@ -25,7 +25,8 @@ twig_config:
|
|||
#
|
||||
date_format: %D %T # Pico's default date format
|
||||
# See http://php.net/manual/en/function.strftime.php for more info
|
||||
pages_order_by: alpha # Change how Pico sorts pages ("alpha" for alphabetical order, or "date")
|
||||
pages_order_by_meta: author # Sort pages by meta value "author" (set "pages_order_by" to "meta")
|
||||
pages_order_by: alpha # Change how Pico sorts pages ("alpha" for alphabetical order, "date", or "meta")
|
||||
pages_order: asc # Sort pages in ascending ("asc") or descending ("desc") order
|
||||
content_dir: content/ # The path to Pico's content directory
|
||||
content_ext: .md # The file extension of your Markdown files
|
||||
|
|
28
lib/Pico.php
28
lib/Pico.php
|
@ -1509,7 +1509,7 @@ class Pico
|
|||
$order = strtolower($this->getConfig('pages_order'));
|
||||
$orderBy = strtolower($this->getConfig('pages_order_by'));
|
||||
|
||||
if (($orderBy !== 'date') && ($orderBy !== 'alpha')) {
|
||||
if (($orderBy !== 'alpha') && ($orderBy !== 'date') && ($orderBy !== 'meta')) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -1525,7 +1525,31 @@ class Pico
|
|||
return $cmp * (($order === 'desc') ? -1 : 1);
|
||||
};
|
||||
|
||||
if ($orderBy === 'date') {
|
||||
if ($orderBy === 'meta') {
|
||||
// sort by arbitrary meta value
|
||||
$orderByMeta = $this->getConfig('pages_order_by_meta');
|
||||
uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order, $orderByMeta) {
|
||||
$aSortValue = isset($a['meta'][$orderByMeta]) ? $a['meta'][$orderByMeta] : null;
|
||||
$aSortValueNull = ($aSortValue === null);
|
||||
|
||||
$bSortValue = isset($b['meta'][$orderByMeta]) ? $b['meta'][$orderByMeta] : null;
|
||||
$bSortValueNull = ($bSortValue === null);
|
||||
|
||||
$cmp = 0;
|
||||
if ($aSortValueNull || $bSortValueNull) {
|
||||
$cmp = ($aSortValueNull - $bSortValueNull);
|
||||
} elseif ($aSortValue != $bSortValue) {
|
||||
$cmp = ($aSortValue > $bSortValue) ? 1 : -1;
|
||||
}
|
||||
|
||||
if ($cmp === 0) {
|
||||
// never assume equality; fallback to alphabetical order
|
||||
return $alphaSortClosure($a, $b);
|
||||
}
|
||||
|
||||
return $cmp * (($order === 'desc') ? -1 : 1);
|
||||
});
|
||||
} elseif ($orderBy === 'date') {
|
||||
// sort by date
|
||||
uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) {
|
||||
if ($a['hidden'] xor $b['hidden']) {
|
||||
|
|
Loading…
Reference in a new issue