Display random posts in WordPress

WordPress posts may be randomly displayed using the “Get random results from a MySql table” tip placed in a simple plugin.

What this plugin does is to simply add the “RAND()” value to “ORDER BY” clause in the sql query which retrieves the WordPress posts.

/*
 * Plugin Name: Randomize posts
 * Plugin URI: http://cristian-radulescu.ro/article/display-random-posts-in-wordpress.html
 * Description: Display random posts in WordPress.
 * Author: Cristian Radulescu
 * Version: 0.1
 * Author URI: http://cristian-radulescu.ro
 */

/**
 * Set the "ORDER BY" value to RAND()
 *
 * @param string $orderby
 *
 * @return string
 */
function rand_posts_orderby_request($orderby) {
  return 'RAND()';
}

// add custom action to WordPres filters
add_action('posts_orderby_request', 'rand_posts_orderby_request');

In order to use the plugin, just place the above code in a file, upload it to your WordPress plugins directory and activate it. If you use cache related plugins it may be necessary to disable them to view the randomized posts.

About Cristian Radulescu

PHP // MySql // Linux // Android
This entry was posted in MySQL, PHP, Programming, WordPress and tagged , . Bookmark the permalink.

2 Responses to Display random posts in WordPress

  1. sam2001 says:

    I’ve been using the Rand code for a while now but i can’t get it to work with the latest version of wordpress (3.2.1) have you noticed this? do you have any fixes or alternatives?

  2. @sam2001 The random plugin works on my WordPress installation. Your issue might be related with a WordPess cache plugin like WP Super Chache

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>