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.