Aug 12

Display 5 random posts in Wordpress

Scribbled on Tuesday, August 12th, 2008

Using plugins for every litte thing in Wordpress is a really bad idea. At least I like to have my own solution before anyone else’s. So I read wordpress function reference and database schema. At first it seemed so easy that I thought why would anyone make a plugin for this. Here is the first code that is itself given in Wordpress site to display random posts.

Solution 1 (Failed for me):

[sourcecode language='php']
$rand_posts = get_posts('numberposts=5&orderby=rand');
foreach( $rand_posts as $post ) :
?>

  • Failed too):

    [sourcecode language='css']
    have_posts()) : $recent->the_post(); ?>

  • Yay It worked !!!):

    [sourcecode language='css']

    $querystr = "SELECT * FROM (SELECT wposts.* FROM $wpdb->posts wposts WHERE wposts.post_status = ‘publish’ ORDER BY rand()) as y limit 5 “;

    $pageposts = $wpdb->get_results($querystr, OBJECT);

    ?>


  • posts wposts WHERE wposts.post_status = ‘publish’ ORDER BY rand()) as y limit 5 [/sourcecode]

    is a nested subquery where the query inside the brackets retrieves the posts that are published (it includes published pages too) and then order it by random. This randomly ordered list is then used to retrieve 5 first posts.

    See the result at the bottom of this website ;p

    Though I haven’t tested the performance but it works fine here.


    Enjoyed this post? Subscribe to Full Feeds or by Email and receive free daily updates on this Blog.

    No related posts.

    Related posts brought to you by Yet Another Related Posts Plugin.

    1. 5 Responses to “Display 5 random posts in Wordpress”

    2. 1

      Cool man!! i was thinking of such a tool in the morning, wondering where i can get it! thnx…

      By Su on Tue 12th Aug, 2008

    3. 2

      Whoooooooosh!
      Right over my head! :D Didn’t understand a word! hehehe…

      By Nikhil on Wed 13th Aug, 2008

    4. 3

      @Su
      But can u really edit the php files. I think your wordpress blog is free and it doesn’t allow editing files etc.

      @Nikhil
      Don’t worry, anytime you need help just mail me.

      By T on Wed 13th Aug, 2008

    5. 4

      @T : i tried it out and it didnt work… i’m not into programming and so couldn’t figure out the problem… :(

      By Su on Sat 16th Aug, 2008

    6. 5

      @Su
      But I suppose you are using Free Wordpress Blog and it doesn’t allow you to save the changes made in code or CSS.

      By T on Sat 16th Aug, 2008

    Post a Comment

    August 2008
    M T W T F S S
    « Jul   Sep »
     123
    45678910
    11121314151617
    18192021222324
    25262728293031