Jens Oliver Meiert

Use my latest work: latest tech book · latest non-tech book · latest optimization tool · latest defense tool

How to Provide a “Random Post” Feature With Eleventy and PHP

Published on Jun 2, 2026, filed under . (Share this post, e.g., on Mastodon.)

Have you ever thought about providing a “random article” feature on your website?

And, are you using Eleventy on a PHP-enabled server?

Then this is for you, a quick way of providing a URL to return a random article.

1. Drop the URLs of Your Posts in a PHP File That Randomly Redirects to These URLs

Save the following where you need it (.njk), and adjust where you want to export the output (here: /random/index.php):

---
eleventyExcludeFromCollections: true
permalink: /random/index.php
---
<?php
$posts = [
{%- for post in collections.posts %}
{%- if post.url %}
  '{{ post.url | absoluteUrl(metadata.url) }}',
{%- endif %}
{%- endfor %}
];

header('Cache-Control: no-store');

if (!empty($posts)) {
  header('Location: ' . $posts[array_rand($posts)], true, 302);
} else {
  header('Location: https://meiert.com/', true, 302);
}
exit;

In brief, the file:

2. Link and Feature the Script

Not much more to see here—link your /random or how you’ve called it, and tell others about the feature!

_ If you want to see this in action, here are three examples: WebGlossary.info uses this solution to provide random terms, meiert.com—this site—gives you random articles of mine, and Haiku Haiku Love, an old heartbreak project where this is done just via PHP, returns random haiku!

About Me

Portrait sketch of Jens Oliver Meiert.

I’m Jens (long: Jens Oliver Meiert), and I’m an engineering lead, guerrilla philosopher, and indie publisher. I’ve worked as a technical lead and manager at various companies (e.g., Google); I’m an active web and tool developer (code optimization, digital defense), a contributor to web standards (like HTML, CSS, WCAG), and a book author (O’Reilly, dxsrc). You’ll like my work if you value pragmatic, proactive problem-solvers. Let’s connect.