Adding a Random Post Button to Kirby
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
go($randomPost->url());
}
]
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 https://yoursite.com/random-post
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:
- Takes all the children of the
blog
page (you will need to change this to wherever your posts live if they're at a different location) - Shuffles all the children of the blog, and selects the first one
- Visits the URL of that random post
If you wanna try it yourself, clickerty click (or taperty tap) this button:
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.
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:
The Name of the Wind
22 Dec 2022
Why Are Newsletters So Painful?
25 Apr 2022
Destroyer of Worlds
17 Apr 2024
Subscribe via email
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