Oct
19
2009
Display Random Posts in WordPress
I am working on a new WordPress site and I wanted to display a selection of random posts at the bottom of every page. It is pretty simple to do, but I also wanted to make sure that on single post pages, the current post would be excluded. That took a little bit more figuring out but I got it working.
Here is a quick piece of code to insert into your WordPress templates so that you can display a list of random posts, excluding the current post that is displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php global $post; $postid = $post->ID; $args = array( 'orderby' => 'rand', 'showposts'=>5, 'post__not_in'=>array($postid) ); query_posts($args); echo '<ul>'; while (have_posts()) : the_post(); echo '<li><a href="'.get_permalink().'" title="'.the_title('','',false).'">'.the_title('','',false).'</a></li>'; endwhile; echo '</ul>'; ?> |
You can always change the number of random posts displayed by increasing or decreasing the ‘showposts’ variable. You can also make it category specific by adding a 'cat'=>24, to the $args array, where ’24′ is the category ID.



Please tell us how to make a conclusion of a random post in WordPress only in the sidebar, without changing the basic news feeds
Thanks
Hello!
Excellent, kind of works…
where actually do i add ‘cat’=>24,?
thank you
That goes into the $args array so it would look like this:
What is the byline code for this… can one help me pls…
What are you referring to by “byline code”?
hi there, this is great stuff. But is there a way by which we could add an excerpt to this? That would make it so much more AWESOME!
You could always add
get_the_excerpt()function at the end of the list item like this:Hi,Thanks for the post but can you tell me how to add random post with thumbnail?
If you have set the Featured Image, you can use the
the_post_thumbnail()function to display the post image.http://codex.wordpress.org/Function_Reference/the_post_thumbnail
This is how I used this (very useful!) code and added thumbnails to it:
http://www.arciris.com/design-and-blogging/wordpress-random-posts-thumbnails/
You can see it in action in the sidebar here:
http://guyjames.com
How is this better or worse than using any of those ‘related posts’ plugins that now are available for WordPress blogs?
Using a plugin is great. But I am a programmer so I like to share simple pieces of code that I use, in case other people out there might want to use it instead of adding another plugin to their blog.
I’ve just cut & pasted the code to a text file for use in the future on the blogs I create … thanks for sharing it
Thanks for this codes, I made some changes and it works fine.. Thanks for sharing, I really appreciate your effort and idea!
I really love the code really helpful But I’m searching for much advance code with thumbnails and I hope screenshots are available as well.