Displaying content in a random order is a common requirement for modern websites. Whether you are building a 'Meet the Team' page, a featured testimonial slider, or a 'Related Articles' section, showing a fresh selection of entries on every page load can significantly improve user engagement and site discovery.
In Craft CMS, achieving this functionality is straightforward once you understand how the Entry Query builder interacts with the underlying database. In this guide, you will learn the modern syntax for randomizing entry results, why certain older methods are deprecated, and the performance considerations you should keep in mind for larger sites.
Using the orderBy Method for Randomness
To order entries randomly in Craft CMS, you utilize the orderBy() method within your entry query. Because Craft CMS is built on top of the Yii2 framework and typically uses MySQL or PostgreSQL, you can pass raw database functions directly into this method.
For most environments, the SQL function RAND() is the key. Here is how you implement it in your Twig templates:
{# Fetching random entries from the 'team' section #}
{% set entries = craft.entries()
.section('team')
.type('mainPeople')
.orderBy('RAND()')
.all() %}
{% for entry in entries %}
<div class="person-card">
<h3>{{ entry.title }}</h3>
{# ... other fields ... #}
</div>
{% endfor %}
By passing 'RAND()' to the orderBy() method, you are telling the database to assign a random value to each row in the result set and then sort the rows based on those values before returning them to Craft.
Important: order() vs. orderBy()
If you are looking at older Craft CMS tutorials or legacy codebases, you might see the .order() method being used. It is important to note that .order() was deprecated in Craft CMS 3 and has been completely removed in Craft CMS 4 and 5.
Always use .orderBy() in modern development. The syntax is nearly identical, but orderBy() provides better alignment with the underlying Yii Query Builder and ensures your code remains compatible with future updates.
Incorrect (Deprecated):
{% set entries = craft.entries.section('team').order('RAND()').all() %}
Correct (Modern):
{% set entries = craft.entries.section('team').orderBy('RAND()').all() %}
Performance Considerations for Large Datasets
While orderBy('RAND()') is incredibly convenient, it comes with a performance cost. When you tell a database to order by a random value, it must generate a random number for every single row that matches your criteria before it can perform the sort.
On a section with 50 entries, the impact is negligible. However, if you are querying a section with thousands of entries, this can lead to significant database overhead and slower page load times.
Optimization Strategies
- Limit the Result Set: Always use the
.limit()method if you only need a few items. While the database still has to randomize the rows, Craft will only process the specific number of elements you requested. - Template Caching: Use the
{% cache %}tag around your random logic. You can set the cache to expire every hour or every day so that the "randomness" is still dynamic but doesn't trigger a heavy database hit on every single visit. - Fetch IDs First: For extremely large datasets, some developers prefer to fetch all entry IDs, shuffle the array in Twig or a custom plugin, and then fetch only the specific entries needed by their IDs.
Example: Featured Random Testimonials
Let’s look at a practical example where we want to display exactly three random testimonials from a specific category.
{# Fetch 3 random testimonials #}
{% set featuredTestimonials = craft.entries()
.section('testimonials')
.orderBy('RAND()')
.limit(3)
.all() %}
{% if featuredTestimonials|length %}
<section class="testimonials-grid">
{% for testimonial in featuredTestimonials %}
<blockquote class="testimonial-item">
<p>{{ testimonial.quoteText }}</p>
<footer>— {{ testimonial.clientName }}</footer>
</blockquote>
{% endfor %}
</section>
{% endif %}
Frequently Asked Questions
Does RAND() work on PostgreSQL?
Yes, RAND() is standard for MySQL. If your Craft CMS installation is running on PostgreSQL, you should use RANDOM() instead: .orderBy('RANDOM()'). Craft does not automatically translate these specific string-based function calls, so check your environment variables if you are unsure which database driver you are using.
Can I combine random ordering with other parameters?
Absolutely. You can chain .orderBy('RAND()') with any other element criteria, such as .search(), .relatedTo(), or custom field queries. Just remember that the randomization happens at the very end of the filtering process.
Is there a way to shuffle an array in Twig without the database?
Yes, if you have already fetched a collection of entries and want to randomize them within the template, you can use the shuffle filter (provided by the Craft CMS core or certain plugins depending on your version). However, orderBy('RAND()') is usually more efficient if you only want to pull a small subset of a large group.
Wrapping Up
Randomizing entries in Craft CMS is a powerful way to keep your site content feeling fresh and dynamic. By using the .orderBy('RAND()') method, you can easily implement this feature in your Twig templates. Just remember to use the modern orderBy syntax rather than the deprecated order method, and keep an eye on performance if your entry counts begin to climb into the thousands.
By following these best practices, you ensure a fast, engaging experience for your users while maintaining clean, forward-compatible code.