Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Display Random Posts from Specific Tags or Categories in WordPress

When developing the colorful Quintessential Theme (opens in new tab), I initially planned on displaying five random posts from each of my most popular tags and categories in the super-slick sliding-panel sidebar. Because I am running an older version of WordPress, however, this task proved to be quite the educational experience.

In newer versions (from 2.5 I think) of WordPress, the query_posts() function enables users to display posts in random order using the orderby=rand parameter. This would have made my life easy, as I could have included the following code for each of my random post lists:

<ul class="random-posts">
	<?php query_posts('tag=whatever&showposts=5&offset=0&orderby=rand'); ?>
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	<li>
		<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
	</li>
	<?php endwhile; endif; ?>
</ul>

This would have been great, but the random-post ordering doesn’t work for my particular version of WordPress. As it turns out, for older versions of WordPress that are missing the incredibly useful orderby=rand parameter for the query_posts() function, there is an unofficial plugin available in the WordPress Help Forums that imparts the orderby=rand functionality to the query_posts() function, thereby enabling users of pre-2.5 versions of WordPress to implement their own random post loops.

For those of you who would like to setup some random post loops on your own site, here’s how to do it in two easy steps. (Remember, this is only necessary if the above method does not work for your particular version of WordPress.)

Numero Uno: Upload and activate the plugin

Copy & paste the following code into a file named “random-posts.php” (or whatever), upload it to your /wp-plugins/ directory, and activate it via the Plugins panel in the WordPress Admin:

<?php
/*
Plugin Name: Random Posts Query
Description: Imparts random display functionality to posts generated via 
query_posts in older versions of WordPress (especially great for version 2.3)
Author URI: http://wordpress.org/support/topic/70359?replies=3#post-444323
*/

// usage: include "random=true" as a parameter in your query_posts loop

function query_random_posts($query) {
	return query_posts($query . '&random=true');
}
class RandomPosts {
	function orderby($orderby) {
		if (get_query_var('random') == 'true')
			return "RAND()";
		else
			return $orderby;
		}
		function register_query_var($vars) {
			$vars[] = 'random';
			return $vars;
		}
}
add_filter('posts_orderby', array('RandomPosts', 'orderby'));
add_filter('query_vars', array('RandomPosts', 'register_query_var'));
?>

Numero Dos: Include and customize the template code

Once the plugin is in place, create multiple tag-specific and category-specific random-post lists by placing the following code after the main loop in your theme template file (e.g., the sidebar.php file):

<ul class="random-posts">
	<?php // use tag=whatever or category_name=whatever for cat/tag-specific posts ?>
	<?php query_posts('tag=whatever&showposts=5&offset=0&random=true'); ?>
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	<li>
		<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
	</li>
	<?php endwhile; endif; ?>
</ul>

Before uploading, make sure you customize this code according to your needs. Old heads feel free to knock the boots, while newer chaps may benefit from the following information:

  • As mentioned in the code comments, replace the “tag=whatever” parameter with the name of the tag for which you would like to display random posts.
  • To display random posts from a specific category instead of a specific tag, simply replace the tag=whatever parameter with category_name=whatever and change the name to your chosen category.
  • Adjust the other query_posts parameters as needed to accomplish your post-display goals. For example, you may also want to display the post excerpt for each post item by including the the_excerpt() tag.
  • Note that this code is essentially the same as that given for newer versions of WordPress; the only difference being that you use the orderby=rand parameter for newer versions of WordPress (where the plugin is not required), and random=true for older versions (where the plugin is required).
  • Placing additional query_posts() loops after the main loop may result in unintended paging and/or plugin issues, so make sure to place it after the main loop.
  • To create multiple lists of random posts, simply create multiple instance of this loop and change the category or tag parameter names to suit your needs.

Time to chill

That concludes this brief retro-tutorial. Although it may not be of much use to those treading the perpetual “upgrade” treadmill, it will hopefully provide some relief for randomizing posts in older WordPress versions.

About the Author
Jeff Starr = Fullstack Developer. Book Author. Teacher. Human Being.
GA Pro: Add Google Analytics to WordPress like a pro.

27 responses to “Display Random Posts from Specific Tags or Categories in WordPress”

  1. orderby=rand increase msql query.how to minimalize it in wordpress?

  2. great tutorial!

    im not familiar with programming and i am confused where i should place those codes if i have a custom template also do you know if this is compatible with wordpress 3.3. I am using magazine-basic template . please, advice!!

  3. navid shayeste 2012/11/30 6:49 am

    Thank you. I’ve used it:

    <?php query_posts('tag=picture&showposts=5&offset=0&orderby=rand'); ?>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    
    <?php
    	$thumb = get_post_thumbnail_id();
    	$img_url = wp_get_attachment_url( $thumb,'full' ); //get full URL to image (use "large" or "medium" if the images too big)
    	$image = aq_resize( $img_url, 220, 170, true );    //resize & crop the image
    ?>
    
    <a href="<?php the_permalink(); ? rel="nofollow">"><img src="<?php echo $image ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" ></a>
    
    <?php endwhile; endif; ?>
Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
WP Themes In Depth: Build and sell awesome WordPress themes.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.