Hexo文章置顶的方法

  |     |   本文阅读:

转载自liuxuewne.github.io

Hexo 默认只提供了按发布日期的降序来排序,通过在 Hexo github 的 issue 里找到了解决办法,原理:在 Hexo 生成首页 HTML 时,将 top 值高的文章排在前面,达到置顶功能,以下解决方法在Hexo 3.3.6 上修改相关文件。

修改 Hexo 文件夹下的 node_modules/hexo-generator-index/lib/generator.js文件

找到该文件后,添加以下代码:

posts.data = posts.data.sort(function(first, second) {
   if (first.top && second.top) { // 两篇文章top都有定义
        return first.top == second.top ? second.date - first.date : second.top - first.top //若top值一样则按照文章日期降序排, 否则按照top值降序排
    } else if (first.top && !second.top) { // 以下是只有一篇文章top有定义,将有top的排在前面
        return -1;
    } else if (!first.top && second.top) {
        return 1;
    } else {
        return second.date - first.date;  // 都没定义top,按照文章日期降序排
    }
    });

更改后的完整代码如下:

'use strict';
var pagination = require('hexo-pagination');
module.exports = function(locals) {
  var config = this.config;
  var posts = locals.posts.sort(config.index_generator.order_by);
    posts.data = posts.data.sort(function(first, second) {
        if (first.top && second.top) { // 两篇文章top都有定义
            return first.top == second.top ? second.date - first.date : second.top - first.top //若top值一样则按照文章日期降序排, 否则按照top值降序排
        } else if (first.top && !second.top) { // 以下是只有一篇文章top有定义,将有top的排在前面
            return -1;
        } else if (!first.top && second.top) {
            return 1;
        } else {
            return second.date - first.date;  // 都没定义top,按照文章日期降序排
        }
    });
  var paginationDir = config.pagination_dir || 'page';
  var 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 代码可能有些区别;添加的代码跟版本无关。

在需要置顶的文章的 front-matter 中添加 top 值

top 值越大,文章越靠前,举例如下:

title: miho-主题安装和配置详情
date: 2017-08-01
categories: 开源项目
author: MinHow
tags:
    - 博客
    - 开源项目
cover_picture: https://cloud.minhow.com/images/miho/theme/github-second.jpg
top: 1

原文链接

文章目录
  1. 1. 修改 Hexo 文件夹下的 node_modules/hexo-generator-index/lib/generator.js文件
  2. 2. 在需要置顶的文章的 front-matter 中添加 top 值
本站到访 | |