Getting a Random Post at Compile Time in Jekyll

While pure Jekyll cannot do true random links to posts at page access, it is possible to insert a link to a random post at site compile time.

At it’s most basic, this can be done with the following liquid snippet which will select a random post from the ‘site.posts‘ collection and then insert that post’s title into the page. This can be expanded to extract other pieces of data from within the ‘post‘ object as you desire.

{% assign somePosts = site.posts | sample: 1  %}
{% for post in somePosts %}
    {{ post.title }}
{% endfor %}

Upping the value of ‘sample: 1‘ will return most posts. The ‘for-in‘ statement will then loop over each of the additionally selected posts.

An example of this in action can be seen as part of the ‘You may also enjoy…’ section of this ‘Retro Computer Adverts‘ post.

Leave a Reply

Your email address will not be published. Required fields are marked *