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 Answers 2

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.

2
  • 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, 2020 at 14:01
  • @JMKelley just added another option for you
    – Oli
    Mar 5, 2020 at 14:25
0

You can use the orberBy('RAND()') function. I learned this one just the other day. (It might only be for Craft CMS 4)

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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