Show Random Posts Anywhere in WordPress

You already know how to display most recent posts anywhere in wordpress. To show random posts, you can use the following code snippet,

<ul>
<?php
$rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) :
?>
<li><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>

Paste this code anywhere in wordpress template files and it will display five random posts. To display more, or less, then five random posts, just change the number 5, to any other number you like. For instance, the following code will display 3 random posts,

<ul>
<?php
$rand_posts = get_posts('numberposts=3&orderby=rand');
foreach( $rand_posts as $post ) :
?>
<li><a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</li>
<?php endforeach; ?>
</ul>

As noted earlier, don’t just paste this code in sidebar widgets or post/pages. Paste it in template files.

To use it in sidebar widgets or post/page body, you need to install Exec-PHP plugin.


Got something to say?

Wordpress installation, upgrade, plugins and theme development are my forte. If you want to spend more time blogging and less time fiddling with your templates, plugins and technical issues, I can help. Find out more about my services, then contact me.

Wordpress Tips, Tricks & Hacks!

Make Money With Wordpress!

Try Aweber for $1 Studiopress Themes

News!