1

I'm trying to create a "Hack Job" version of Similar Entries, I'm using the following code but it seems to be getting the same entries over and over again. I know shuffle function does this, but I thought it'd be shuffling through the entire array of Entries?

{% set nextEntries = shuffle(craft.entries.section('merchants').id('not ' ~ entry.id).limit(15)) %}

I'm looking to make it grab a random 15 entries from the merchants section, which I will then cache.

Any help would be great.

2

You're always getting the same set because the entries are first fetched, then shuffled. To achieve what you want, you could do:

{# get all your entries ids #}
{% set allIds = craft.entries().section('yourSection').ids() %}
{# Shuffle all and slice to just 15 #}
{% set shuffledIds = shuffle(allIds) | slice(0,15) %}
{# Fetch your random entries #}
{% set entries = craft.entries.id(shuffledIds).all() %}

Or

{# get all your entries ids #}
{% set allIds = craft.entries().section('yourSection').ids() %}
{# Fetch your random entries #}
{% set entries = craft.entries().id(shuffle(allIds) | slice(0,15)).all() %}

In response to your comment then you could do something like the below:

{# set a random offset #}
{% set offset = random(0, 6000)%}

{# set a random sort #}
{% set orderBy = random(['postDate', 'id', 'title']) %}

{# set a random direction #}
{% set direction = random(['ASC', 'DESC']) %}

{# get 500 ids #}
{% set allIds = craft
            .entries()
            .section('posts')
            .offset(offset)
            .orderBy(orderBy ~ ' ' ~ direction)
            .limit(500)
            .ids() %}

{# Fetch your random entries #}
{% set entries = craft.entries().id(shuffle(allIds) | slice(0,15)).all() %}

With this, you only fetch 500 entries with a random offset and sorting, shuffle that pool and pick 15. This might not be as random but I doubt you'd notice it.

| improve this answer | |
  • Due to it being a fairly large site with over 8k entries. Would this cause strain to fetch this many ID's? – JMKelley Mar 5 at 14:01
  • @JMKelley just added another option for you – Oli Mar 5 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.