11

I'm trying to pull a random entry from among an array of sections, but I can't get it to work.

I tried the code below, but I'm just getting errors. I've tried multiple ways of listing the sections -- "section","section" ['section,section'],etc, but none work. Do I need to specify my sections in a different way?

{% set random = craft.entries.section('quotes,didYouKnow').limit(1).order('RAND()').find() %}
{% for content in random %}
...
{% endfor %}
18

According to the docs, you can pass an array into the "section" parameter:

{% set entries = craft.entries.section(['quotes','didYouKnow']) %}

There are several ways to get a random entry, but the method you've chosen is a very good one, because it randomizes during the initial SQL call:

.order('RAND()')

Lastly, you can cut out some of the extra legwork from your original example by calling first instead of find:

{% set entry = craft.entries.section('mySection').first() %}

When you retrieve your entry using first, you'll get a single entry instead of an array of entries. You can skip the for loop entirely, since you're already dealing with a single entry.

So to put that all together...

{% set randomEntry = craft.entries.section(['quotes','didYouKnow']).order('RAND()').first() %}

<h1>{{ randomEntry.title }}</h1>

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.