There's a Liquid filter sample
that allows you to "pick a random value from an array. Optionally, pick multiple values". (See documentation here)
My use case is to have a photo journal for viewers to click and generate one random post from my existing collection "photodiary", and not repeat the post in the next click.
Here's my code:
{% assign posts = site.photodiary | where_exp:"post", "post.url != page.url" | sample: 8 %}
{% for post in posts limit:1 %}
<a class="prev" href="{{post.url}}">Load a post</a>
{% endfor %}
</div>
<main>
{%- if page.content-type == "photodiary" -%}
<h2>{{page.title}}</h2>
<p> {{content}} </p>
{%- endif -%}
</main>
Currently I only have 8 entries, hence the sample: 8
.
While the code works, after 1-2 clicks, the posts will be repeated and my page will only load the same 2 to 3 posts.
Can anyone let me know if there's a flaw in the logic or my code? Thanks much!