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.

 'rand',
   'posts_per_page' => 5,
   'post__not_in' => array( $post_id )
);
$rand_query = new WP_Query( $args );
echo '
    '; while ( $rand_query->have_posts() ) : $rand_query->the_post(); echo '
  • ' . the_title() . '
  • '; endwhile; echo '
'; ?>

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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie