How to display random posts in the WordPress Loop

When displaying posts, sometimes it is helpful to use query_posts to display certain content from your site. This is especially useful when you are using WordPress as a CMS.

<?php query_posts("showposts=8&cat=49&orderby=rand"); ?>

			<?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?>

				<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>

				<div class="body">

					<?php the_content(); ?>

				</div><!--body-->

			<div class="meta">

				<div class="left">

					<p>Posted: <?php the_time(); ?> in <?php the_category(', '); ?> <?php comments_popup_link('No comments yet', '1 comment so far', '% comments so far (is that a lot?)', 'comments-link', 'Comments are off for this post'); ?></p>

				</div>

			</div><!--meta-->

				<?php comments_template(); ?>

				<?php endwhile; ?>
				<?php else : ?>
				<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
				<?php endif; ?>

In the first line, I say show me eight posts, from category 49, then order them in a random order. Nice and simple way to display random posts.

What you could do, is build a page that simply adds

<?php query_posts("orderby=rand"); ?>

And you would be given a random post whenever you landed on it.


Tagged with , , ,

Posted by Jake Spurlock February 8th, 2010 — 1 Comment