
What about giving a new life to your old blog posts? In this recipe, I’m going to show you how to easily display a random post on your blog sidebar.

What about giving a new life to your old blog posts? In this recipe, I’m going to show you how to easily display a random post on your blog sidebar.
To achieve this recipe, simply paste the following code on he sidebar.php file of your theme:
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post();
the_title();
the_excerpt();
endwhile;
endif; ?>
That's all. Your sidebar will display a random post on each of your blog pages.
24 Responses
Exactly what I need but I have 2 problems :
- there are no links to the post ;
- 2 posts are displayed in the list ;
Thanks for helping me !
Same as Maigret. I need a link to the post. It shows up as one post okay for me. Thanks!
To create a link to the post, just use <a href=”<?php the_permalink();?>”>my link is here</a>
Thanks, it works perfectly !
wow! great.
could you please show me, how to create tab based options in sidebar. even how i can input this tab features in below of the posts. that be will great.
Is it possible to add this in a text widget?
@Plurkr: There are plugins that let you add php to text widgets should look into that.
Great stuff as usual.
Makes my sidebar disappear. Here’s the code I’m using:
Today’s random post:
‘rand’, ‘showposts’ => 1));
if (have_posts()) :
while (have_posts()) : the_post();
<a href=”">
endwhile;
endif; ?>
What am I doing wrong?
Sorry, it looks like the php code got chewed up. Anyway, this code worked for me:
<?php $myposts2 = query_posts(array(‘orderby’ => ‘rand’, ‘showposts’ => 1));
foreach($myposts2 as $post) : ?>
<a href=”"></a>
<?php endforeach; ?>
Thanks
It works! But how to make link to this random post from title to be shown?
@Hungry Forester: Please read my first comment, I have already explained it
A warning for larger sites: sorting by rand() is very expensive for a database to perform as it can’t use an index. Even for smaller blogs, don’t be surprised if you see your load go up.
There are various better approaches but they’re more involved. Most blogs will find it usable enough.
Artem
Hey, nice, this is what im looking for. but just like Maigret said, 2 posts are displayed in the list.
The first one is at the top of the page. this is where i place the code.
and the second one is at the bottom of the page. i dont place any random code there.
anyone can help
btw nice code. thanks.
Hi, This is almost exactly what I am looking for, thanks.
How would I change it so that it shows only the single most recent post?
Nice one man!
I made this trick with this code:
‘rand’, ‘showposts’ => 10));
foreach($myposts as $post) :
?>
<a href=>
That is so easy! I cannot believe I have been struggling with this for so long. Thanks.
Trackbacks: