3
votes

For someone that updates posts very often it's necessary to have posts sorted from new to old based on last modification date instead of Jekyll's default sort by posted date.

There seems to be no easy way of accomplishing this. I've read and tested pretty much all methods out there.

Here's what worked (partially as expected):

Used this gem https://github.com/gjtorikian/jekyll-last-modified-at but now I have to manually enter last_modified_at in each post's front-matter in order for Jekyll to sort the posts using this loop:

{% assign sorted_posts = site.posts | sort: "last_modified_at" | reverse %}
{% for post in sorted_posts %}
<!-- CODE HERE -->
{% endfor %}

The issue is having the last_modified_at inside each post as it stops the plugin from auto-setting that value every time I hit CTRL+S to save a post.

Is there any way I can automate this?

1

1 Answers

1
votes

EDIT: It only works in DEVELOPMENT, not sure why it doesn't work in production as well. It updates ALL posts with the same date whenever I deploy the website.

I'm very thankful for hooks and this post ofc: https://stackoverflow.com/a/36769049

Steps:

  • created new file in _plugins folder named hook-add-last-modified-date.rb
  • paste this code inside it and save:

    Jekyll::Hooks.register :posts, :pre_render do |post|
    
    # get the current post last modified time
    modification_time = File.mtime( post.path )
    
    # inject modification_time in post's datas.
    post.data['last-modified-date'] = modification_time
    
    end
    
  • when I hit CTRL+S on a post now 2 things happen: a) updates the last modified date wherever I have {{ post.last-modified-date | date_to_xmlschema }} and b) it bumps it to the top of my posts on the index page because it is sorting by that variable.

Love you guys!