Random Posts – take a Lucky Dip
This morning I had the idea of writing a post on a random subject, but then wondered how I would generate that subject. I could take a Lucky Dip in the dictionary or even create a script for generating random words to get the juices flowing. I thought that in addition to my usual topics I could write a random unrelated post, just to keep up that spirit of being spontaneous as some people like it call it.
The other thing that I thought of was that on Wikipedia there is a link to view a random article and thought it might be fun and interesting to do that on my blog too. There aren’t a huge amount of articles and posts on this blog as I’ve only been going for a year, but certainly enough to take a lucky dip. In the sidebar under the search field there is new section that I’ve called Random Post. Under that there is a link called Take a Lucky Dip. Clicking on that link will take you to a random post or give a 404 error.
Here’s how I did it
As I’m quite new to php and have been teaching myself during my weekly sessions at the library with my tutor book, I wanted to try something simple. I used the mt_rand() function to generate a random number between 1 and 126. This number corresponds to the ID of the post. And as my blog archives are set up to be numerical it was pretty easy to do. Here’s the code snippet:
<li><h2>Random Post</h2>
<?php // Generates a random post link
$archive_no = mt_rand (1, 126); // will need to update when I add new posts ?>
<p><a href="http://arupdesigns.co.uk/blog/archives/
<?php echo $archive_no; ?>">***Lucky Dip***</a></p>
</li>
I’ve only made a couple of changes since the first draft which is to change the anchor text to Take a Lucky Dip. And I’ve added a title attribute saying that you may end up with a 404 page.
If you want to have a go on your blog then you can simply copy and paste the code into your sidebar file or wherever you want the link to appear and change the anchor text too. You’ll also need to change the way your blog displays urls. Each time the page is refreshed a new random link appears.