Show Random Posts In WordPress
As you may have noticed at the bottom of my theme pages I show 3 “Random” themes that will switch every time the page is refreshed.
This allows me not only to show you a few themes you may not have seeing before, but it also helps spread out links across the site. When a search engine crawls the site they will see different links on each page as opposed to having the same “newest” or “popular” posts across your whole site.
The method to Show Random Posts is actually very easy and can be achieved with a simple call to the database. Plus, there are a few wordpress template tags that you can use for various effects.
Display Random Posts
Simply insert the following code where you want them to appear.
The Template Tag
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=3'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php } ?>
</ul>
The Full Code
<div id="randomposts">
<h3>Random Posts</h3>
<ul>
<?php $posts = get_posts('orderby=rand&numberposts=3'); foreach($posts as $post) { ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
</li>
<?php } ?>
</ul>
</div>
Tweaking
As you see in the “Full Code” I have gone ahead and added a whole div container for the random posts as well as an h3 title tag. This way you can go into your stylesheet and make some changes so that you can display them the way you want.
If you notice the code you will also see that we have chosen to display “3″ random posts. You can change this number to whatever you want.
Some useful tags
You can use the following arguments within the brackets of the get_posts tag:
numberposts=10 (shows 10 posts..if you set this value to -1 it will show an infinite ammount)orderby=title (orders list by title) category_name=blog (shows only posts in the "blog" category cat="1" (shows posts in the category with an ID of 1) tag=premium (shows only posts with the "premium" tag)order=ASC (shows the list in Ascending order)



