浏览代码

Allow pages to be sorted by arbitrary meta values

This basically works like Pico's `sort_by` Twig filter
Daniel Rudolf 8 年之前
父节点
当前提交
414f5ac18e
共有 2 个文件被更改,包括 28 次插入3 次删除
  1. 2 1
      config/config.yml.template
  2. 26 2
      lib/Pico.php

+ 2 - 1
config/config.yml.template

@@ -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

+ 26 - 2
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']) {