Adding a Random Post Button to Kirby

15 Jan 2024 | ~2 minute read

I've added a feature where you can click a button and visit a random post. I wasn't able to find this documented with Kirby, so thought I'd share how I did it in case is helps others.

I thought I'd add a random post button to my search page. It's more for fun than anything else; and to give visitors a different way of discovering content.

There's a number of ways to implement a random post button, and this may not be the best way, but it's pretty straightforward and needs no JavaScript. It doesn't even need a button, if you don't want to use one.

What I've done is create a route in my config.php file that redirects /random-post to -- you guessed it -- a random post.

Here's the code you need to add to your Kirby config.php file to make this work:

  'pattern' => 'random-post',
  'action'  => function () {

  // The child collector
  $posts = page('blog')->children();

  // Randomise the children and pick the first one
  $randomPost = $posts->shuffle()->first();

  // Redirect to the random blog post


Ok, so let's talk through what this code is doing.

The pattern is effectively the URL you need to visit to invoke this route. So in this case you would need to visit for this route to take effect. You can change this to anything that makes sense to you.

When Kirby detects a hit to /random-post it then triggers the function we've defined, which does the following:

If you wanna try it yourself, clickerty click (or taperty tap) this button:

Read a random post...

Finally, I'd like to say thanks to Sonja from the Kirby forums for helping me with this. She nudged me in the right direction to come up with a much better solution than I was originally working on.

← The one before
Warming up the Garage 🔥

Up next →
My Thoughts on Kagi Search

Get in touch!

Receiving emails from my readers is my favourite thing, so if you have something to say, feel free to drop me an email or sign my guestbook.

Want more content?

Say no more, dear reader. Here's three random posts from this blog for you to peruse:

I Have a Guestbook
27 Feb 2024

CMS Filesize Comparison
09 Oct 2023

My Predictions For 2022
01 Jan 2022

Want to be informed when I post new articles? Simply enter your email address below and you will get an email whenever new posts are published.

Alternatively, you can subscribe via RSS instead.

Enjoyed this post?

I put a lot of work into maintaining this site and I really enjoy interacting with my readers.

My fuel of choice is coffee, so if you did enjoy this post, or found it in any way useful, I'd appreciate more fuel to keep me going. ❤️

Buy me a coffee