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.
Want more?
So you've read this post and you're still not satisfied? Ok then, here's some other stuff for you to do: