Hexo定制之文章排序

发布时间 2023-10-10 11:22:57作者: CarlZeng
title: Hexo定制之文章排序
date: 2023-10-04 15:55:48
tags: [hexo]
categories: hexo
description: 

主页文章按更新时间排序

针对目前最新的hexo版本
hexo: 6.3.0
NexT version 8.18.1

结合感谢名单中作则的文章,终于,我在node_modules\hexo-generator-index\lib\generator.js文件中找到了似乎是用于排序的代码,
该文件是为了添加文章置顶功能的,但当置顶等级设置相同时,按照发布日期进行排序。
对JavaScript改完之后该文件中的内容如下所示

'use strict';

const pagination = require('hexo-pagination');

module.exports = function(locals) {
    const config = this.config;
    const posts = locals.posts.sort(config.index_generator.order_by);

    //20231004/CZ hexo next 排序 最后编辑
    // posts.data.sort((a, b) => (b.sticky || 0) - (a.sticky || 0));
    posts.data = posts.data.sort(function (a, b) {
        if (a.sticky && b.sticky) { // 当两篇文章top都有定义时
            if (a.sticky == b.sticky) return b.updated - a.updated; // 若top值一样,则按照文章更新日期降序排列
            else return b.sticky - a.sticky; // 否则按照top值降序排列
        } else if (a.sticky && !b.sticky) { // 以下两种情况是若只有一篇文章top有定义,则将有top的排在前面(这里用异或操作居然不行233)
            return -1;
        } else if (!a.sticky && b.sticky) { //上一条已解释
            return 1;
        } else return b.updated - a.updated; // 若都没定义,则按照文章更新日期降序排列
    });

    const paginationDir = config.pagination_dir || 'page';
    const path = config.index_generator.path || '';

    return pagination(path, posts, {
        perPage: config.index_generator.per_page,
        layout: ['index', 'archive'],
        format: paginationDir + '/%d/',
        data: {
            __index: true
        }
    });
};

详细的hexo版本信息:

hexo: 6.3.0
hexo-cli: 4.3.1
os: darwin 21.2.0 12.1

node: 16.13.0
v8: 9.4.146.19-node.13
uv: 1.42.0
zlib: 1.2.11
brotli: 1.0.9
ares: 1.17.2
modules: 93
nghttp2: 1.45.1
napi: 8
llhttp: 6.0.4
openssl: 1.1.1l+quic
cldr: 39.0
icu: 69.1
tz: 2021a
unicode: 13.0
ngtcp2: 0.1.0-DEV
nghttp3: 0.1.0-DEV

感谢思路来源

hexo笔记:文章排序