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>
<?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>
<?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.







