Random Posts

May 27, 2004 8:06pm 62 comments

I wrote up a quickie hack for Sushubh to pull random blog entries from the database. To make it generally useful, I wrote it as a function that takes two arguments:
     random_posts ($catID = 0, $count = 4);By default, it'll grab four random posts from any category. Give it a category ID and/or a specific number of posts to pull in order to change it.

If you know you're not going to use all of the posts' data, you could tweak the last SQL query to grab just the bits you need, instead of everything, thereby easing the load on your database.

Oh yeah, this hack does not honor my per-post user-level restrictions modification. If you're using that, this hack will happily display all your restricted posts.

Not the most useful of hacks, but maybe someone somewhere will put it to good use.

UPDATE: I've made this into a proper plugin for WordPress 1.5 and above. To use it, simply install and activate the plugin, then insert the following code in your template:

<?php
echo "<ul>";
$rp = random_posts($catID, $count);
foreach ($rp as $p) {
$title = get_the_title($p);
$link = get_permalink($p);
echo "<li><a href='$link' title='$title'>$title</a></li>";
}
echo "</ul>";
>

Download random-posts.zip!


Comments so far: Atom feed of the comments for this post

  1. Bob 2004-05-28 08:04:03

    "You can see this hack in action right here." Dead link.

  2. Adam M. 2004-06-01 20:33:53

    This is outstanding! I may be able to move my photoblog over to WP yet!

    Is there any way to make it pull the contents of the excerpt field only?

  3. skippy 2004-06-01 21:17:34

    The random_posts.php function returns all data from the randomly selected posts; so if you want to display just the excerpt, you'd do something like this:

    <?php include_once('./random.php'); ?>
    <?php $posts = random_posts('1'); // or whatever category you want ?>
    <?php if ($posts) { foreach ($posts as $post) { start_wp(); ?>

    <div class="storycontent">
    <?php the_excerpt(); ?>
    </div>

    <?php } } ?>

    You may want to look at your index.php to see how the default page gets generated; and compare index.php with the example random.php on my site.

  4. Elfboy 2004-06-08 14:47:29

    I'm currently working on a hack to randomly delete stupid user comments.

  5. Sushubh 2004-07-19 21:51:19

    I never dropped in to say thanks! :)

  6. Andrea 2005-01-13 08:26:01

    Hi, I'm currently using this hack on a local install of WP. Works like a charm. :-) I'd really like to display the postmeta (from the custom fields) along with the random entry, though. I'm not a coder, otherwise I could probably edit the function to fetch the data from that table as well. Could you maybe tell me in easy words how to do this (if it's possible at all)? Thanks in any case.

    Oh, one more question. Will this still work with WP 1.3/1.5?

  7. skippy 2005-01-13 09:09:10

    I haven't looked at this code in a long time, and I haven't looked at the 1.3/1.5 code at all, so I really don't know if this will work with newer versions of WordPress.

    If you just want to dislpay the meta keys and values, use this: <?php the_meta(); ?>

    See the description of the the_meta() function in the WordPress wiki.

    You might also want to evaluate some of the random plugins, which might provide a nicer interface:http://wp-plugins.net/index.php?filter=random&filter_search=Go...http://wiki.wordpress.org/?pagename=Plugin#random

  8. Emeric 2005-07-26 09:30:20

    hello,

    i'm probably the only one who can't make this work properly...
    i'd love to be able to use your developpement to pull different post at itch reload on my page. But all i get is a bunch of error of all kind everywhere.. when the page load.

    could i have a special treatment in superHelp ? pretty please ?

    thanks for your suscribes2 witch works perfectly so far..

  9. skippy 2005-07-26 19:54:54

    Emeric: it would help immensely if you could describe your problems.

  10. Dave Addey 2005-08-26 08:25:53

    Hi Skippy,

    Great plugin! How would you adapt it to select all posts in a category, *and* that category's subcategories? I really need to do this for a new blog :-)

    Dave.

  11. Kevin 2005-09-01 13:40:31

    I have inserted the code to the template and it gave me an error.

    The error is liek this:

    Parse error: parse error, unexpected T_STRING, expecting ',' or ';' in /homepages/20/d90649014/htdocs/me/wp-content/themes/v4ny38/header.php on line 109

    What is the problem? any help? thanks

  12. skippy 2005-09-01 13:44:49

    Kevin: I goofed my code entry. It should be fixed now in the post above. Please compare that with what you have tried to use. If you still have trouble, please let me know.

  13. Steve Lambert 2005-09-12 02:31:13

    I was trying to get this to work with some luck, but I can't get it to do quite what I want. I was hoping you might be able to help.

    I activated your plugin and added this:on the line above The Loop. It worked. It called random posts from category 4. However, I wanted it to show 12, and it showed 11, or 9, or 8. Everytime I refreshed it showed a different number of posts.

    If you could throw some clues my way I'd appreciate it. Thanks.

  14. skippy 2005-09-12 09:48:10

    Steve: the code you tried to paste got lost. Try again, without the &lt?php and ?> tags, if possible.

  15. Steve Lambert 2005-09-12 15:05:01

    Ok, here goes - I put this above the loop:

    ?php $posts = random_posts('4','12');

    But of course with the proper opening and closing tags.

    Thanks

  16. skippy 2005-09-12 15:28:35

    Steve: okay; the code looks okay. So my guess is that your system is randomly selecting the same post more than once within the same call. My plugin randomly selects a post ID once for each $count variable you supply, and it's completely feasible that the same number will be randomly selected more than once.

    If you absolutely need 12 random posts, I'll need to rework my plugin a bit to ensure that no duplicate random numbers are ever used. It's not terribly difficult, but it's also not something to which I'm going to commit a lot of time. Let me know if this is something you want, and I'll get around to it before too long.

  17. Steve Lambert 2005-09-12 20:46:48

    Skippy,

    Thanks for figuring that out. That is totally something I would want! That would be great. But I have no idea how I would rewrite your plugin. At this point, that is pretty over my head. I can find code and change it, but I wouldn't know how to rewrite it or anything. I don't need it by tomorrow or anything, there's a lot of other work I can do on the site before I add this feature, but if you got to it eventually, that would be cool. Any chance you could email me when it's done? Thanks for your attention.

  18. wewe 2005-10-07 22:17:33

    Parse error: parse error, unexpected '>' in /home/shinesky/public_html/wewe/wp-content/themes/rin/sidebar.php on line 43

  19. heatheer 2005-10-27 13:59:21

    wewe - in the code above it is missing the question mark to close the php at the end: ?>

    (also when you copy and paste the double and single quotes are turned into punctuation marks, and those need to be converted).

    however, i haven't been able to get this plugin to work. i only need one random post from a specific category. i have tried the code seen here, which says 'pleace above the loop'.
    http://wordpress.org/support/topic/40818#post-229530

    so i tried this with the loop:

    <?php
    $p = random_posts('26', '1');
    query_posts("p=$p");
    echo ($p);
    ?>
    <?php while (have_posts()) : the_post(); ?>
    <p><?php the_title(); ?></p>
    <?php the_content(); ?>
    <?php endwhile; ?>

    but i just get a list of posts, from no particular category. and i tried putting single quotes around the category ID, and number and removing them too. no difference..

    when i echo the $p variable i get Array...

    oh, and i tried the code above but i need to get the content for the post, and can't figure out how to do that. a

    anyone got a clue to spare?

  20. skippy 2005-10-29 08:39:58

    Try print_r($p) to see what the array contains. Then you can use $p['foo'] to access the individual array elements.

  21. Thomas 2005-11-05 00:04:15

    I have installed the plugin, but I don't know where "the loop" is--which template file, and do I have to take something out when I put the code above in?

    thanks

  22. skippy 2005-11-05 07:02:46

    Thomas: The loop usually lives inside index.php.

  23. Thomas 2005-11-05 10:43:31

    So I put the code";
    $rp = random_posts($catID, $count);
    foreach ($rp as $p) {
    $title = get_the_title($p);
    $link = get_permalink($p);
    echo "$title";
    }
    echo "";
    >
    above the Loop in index.php?

  24. skippy 2005-11-06 13:56:44

    Thomas: that should work.

  25. Thomas 2005-11-06 19:42:18

    heh heh, I love that word, "should". I'll keep trying.

  26. kat 2006-01-09 11:00:38

    I am getting an error using this code";
    $rp = random_posts($catID, $count);
    foreach ($rp as $p) {
    $title = get_the_title($p);
    $link = get_permalink($p);
    echo "$title";
    }
    echo "";
    >
    My error is:

    Parse error: parse error, unexpected '>' in /www/htdocs/w005f3de/wp-content/themes/ski/home.php on line 58

    I actually want to display a random post from a specif category, not as title but as the actual post. how do I do it?
    thanks

  27. at 2006-01-15 02:40:47

    kat, make sure you close the php argument

    the last bit of code should be "?>" - not just ">"

  28. MW 2006-01-22 02:30:58

    I want to display 4 random posts in the sidebar for my single post view from the same categories that post is in. I also want to be sure that they are unique (not selected more than once) and that the current post is not included in the list. Is that possible using this plugin?

  29. skippy 2006-01-22 19:23:14

    MW: yes, this plugin should do what you want. I haven't tested this with WordPress 2.0, though, so I can't guarantee that it's compatible.

  30. MW 2006-01-24 08:59:35
    I haven't tested this with WordPress 2.0, though, so I can't guarantee that it's compatible.

    Thanks! I'll let you know how it turns out!

  31. Onn 2006-01-30 13:08:39

    is it only allow random post for one category?
    What shall i need to do if i wan to display one random post only and it will select any post in all the categories.

  32. Fred Crowson 2006-02-02 16:15:10

    Nice bit of code. Came here following a link from Rent a Coder for someone who hasn't realised that all they need is:

    in the right place.

    Hope they give you the money!

    Fred
    :~)

  33. Fred Crowson 2006-02-02 16:20:34

    The invisible ink hid the <?php the_content(); ?>

  34. horusprim 2006-02-11 11:38:34

    Does using the random posts plugin trigger WP to ping every time new random post appear on your blog?

  35. Sachin Garg 2006-03-05 18:15:49

    I recently integrated this plugin in the sidebar at http://www.c10n.info, but it seems incomplete without mentioning the Date of the random post.

    All the functions for getting time seem to be tied to the main loop. How can I get post's date without running it in The Main Loop?

  36. Sachin Garg 2006-03-06 15:16:53

    I myself figured how to do this :-)

    $post = get_post($p);
    $time = $post->post_date;
    $time = mysql2date('F jS, Y', $time);
    $time = apply_filters('get_the_time', $time, $d, false);
    echo "$time";

  37. Sal Just Sal 2006-03-12 17:29:04

    I'm getting the following error:

    WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY ID ASC' at line 1]
    SELECT DISTINCT ID from wp_posts INNER JOIN wp_post2cat on (wp_posts.ID = wp_post2cat.post_id) AND (wp_post2cat.category_id = ) ORDER BY ID ASC

    WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1]
    SELECT * FROM wp_posts WHERE

    Warning: Invalid argument supplied for foreach() in /home/oursong/public_html/right/wp-content/themes/green-marinee/index.php on line 42

    Also, has this plugin been tested in 2.0?

  38. Ravan 2006-03-16 18:12:46

    Hi Scott,
    Thanks for another great little (but old ;) ) plugin! Found out it works on WP 2.0!

    So to all who's interested:

    I wanted to display random posts on my frontpage and needed more than the title and permalink. I got it working in by extracting the post-id's from the results and running them through the usual 'Loop' this way:ID;
    query_posts($query);
    if (have_posts()) : while (have_posts()) : the_post(); ?>
    ... ususal standard loop thingies ...

    I suppose there should be a better way (not a work-around like this) but that's for others to figure out :)

  39. Ravan 2006-03-16 18:17:01

    Hmmm, that didn't turn out right... Suppose I should have filtered out the php-code:

    $rp = random_posts();
    foreach ($rp as $p) {
    $post = get_post($p);
    $query = "p=" . $post->ID;
    query_posts($query);
    if (have_posts()) : while (have_posts()) : the_post();

    ... this is "The Loop" so here go your preferred loop thingies ...

    endwhile; endif;
    }

  40. SavedScenes 2006-03-28 16:36:50

    I have been trying to get this to work for a few days now and have been unsucesful. I would LOVE some help. I have been copy pasting the code (given above) into the index file and am getting this error
    "Parse error: parse error, unexpected '>"

    Either I am suppose to alter this code and dont know or am putting it in the wrong spot.

    Thanks!

  41. SavedScenes 2006-03-28 22:06:53

    I added the ? and its now showing a random post link rather then the random post content

  42. Orbitalz 2006-04-25 17:34:03

    Great plugin! It works just fine in WordPress 2.0.2

    However, could you update the plugin to handle this:

    I told the plugin to output 20 random posts. However, I only have 15 posts, so it outputs 5 duplicates.

    Could you make it so it doesn't out duplicate posts?

    This is a feature I truly need badly.

  43. Orbitalz 2006-04-25 18:36:41

    NEED Help!

    How do I get this plugin to work on category pages?

    So when I visit a category, it'll show a random amount of posts from that category.

  44. Dietmar 2006-04-26 15:25:41

    Works great in my Sidebar! (WP 2.0.2)
    Awesome Plungin! Thanks a lot!

    Greetz from Brazil, Dietmar

  45. Crys 2006-05-10 06:48:43

    I attempted to use this and got the following error:

    WordPress database error: [You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1]
    SELECT * FROM wp_posts WHERE

    Warning: Invalid argument supplied for foreach() in /home/dreamsi/public_html/mud/wp/wp-content/themes/neutral/footer.php on line 13

    I don't know php at all, so I'm not quite sure how to fix it. I don't have a sidebar, I just use footer.php for those. I'm trying to display a post from a particular category, with a title, permalink, and excerpt. I don't know what to do with this "Loop" stuff I see everyone talking about, so I'm sure whatever I was supposed to do there is contributing to my error. Any ideas for a newbie? :)

  46. Crys 2006-05-10 07:21:15

    Well, it almost works, except it doesn't display just one:

    <?php
    $p = random_posts ($catID = 4, $count = 1);
    query_posts("p=$p");
    echo ($p);
    ?>

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

    <?php the_excerpt(); ?>
    <?php endwhile; ?>

  47. Geoff 2006-05-16 13:38:16

    I was drawing 3 random posts and as noted above, the duplicates were a pain and resulted in only 2 posts displayed on occasion.

    My fix was this: $sql = "SELECT * FROM $wpdb->posts WHERE ";

    $list=$result ; #range(0,$max);
    shuffle($list);
    $list=array_slice($list,0,$count);

    for ($i = 0; $i < $count; $i++) {

    if ($i == '0')
    $sql .= "(ID = '" .$list[$i]. "')"; #. $result[rand(0,count($result) -1)] . "')";
    else
    $sql .= "OR (ID = '" .$list[$i]. "')"; #$result[rand(0,count($result) -1)] . "')";
    }

  48. Geoff 2006-05-16 13:46:50

    For what it's worth, I also added in a preformatted option to the function so that I need not bother with a loop every time I want random posts. Mine goes like this:

    if($preformat) { $formatted= '';
    foreach ($randomposts as $p) {
    $title = get_the_title($p);
    $link = get_permalink($p);
    $formatted.= "<h5><a href='$link' title='$title'>$title</a></h5>";}
    echo $formatted; return true;
    }
    ...where $preformat is a third variable passed to the function as either true or false.

  49. Crys 2006-05-20 13:57:57

    I tried your fixes Geoff, but I'm not quite sure what I'm doing wrong. The plugin works, but still displays all entries at once. It also displays a default excerpt of the actual post for those that don't have inputed excerpts, but I can get around that. If I could just get it to only display one random post instead of all of them, I'd be set.

  50. Geoff 2006-05-24 03:50:33

    Sorry Crys, my fixes really had nothing to do with the trouble you were having.

    Your code has some problems, and you should look at the example at top. You wrote:

    I'm not sure where you got this but you have the wrong idea.

    You should have in your template:$rp = random_posts(4, 1);
    foreach ($rp as $p) {
    $title = get_the_title($p);
    $link = get_permalink($p);
    echo " $title ";
    }

    Although now I see you'd need to use the loop or a hack of get_the_content so that a permalink could be passed. Well, the random muse appears to be working on your blog. Is it an illusion or how did you solve it?

  51. Crys 2006-05-27 04:41:15

    Oh, this is a different site I'm using this on. On the one you looked at, I'm just displaying the latest entry in a specific category. Not a random entry.

    The page I'm attempting to do this on is mud.adventmud.org
    However the code is not up unless I'm trying to work on it, because otherwise there's just a bunch of errors everywhere. I attempted your fixes too, but I don't believe I'm applying them correctly. I've gotten skippy's to work, just not to display only one:

    ?php
    $p = random_posts ($catID = 4, $count = 1);
    query_posts("p=$p");
    echo ($p);
    ?

    ?php while (have_posts()) : the_post(); ?
    a href=""
    ?php the_title(); ?
    ?php the_excerpt(); ?
    ?php endwhile; ?

  52. Forest 2006-05-27 19:34:42

    I just implemented, having used before, but noticed it was posting a draft along with published posts. Disconcerting.

    Any suggestions on eliminating posts saved as draft.

    Also interested in how to scan all posts only, and not pages?

  53. Geoff 2006-05-28 16:53:06

    There are a few erros in your code. First, you need to pass variables and the syntax of random_posts ($catID = 4, $count = 1); is incorrect. You want random_posts (4,1);

    I see that you are copying the syntax from the function but that is incorrect. Second, random_posts() returns an array. Using query_posts("p=$p"); isn't likely to work because of that.

  54. Geoff 2006-05-28 16:57:08

    Looking at the post for this plugin, I can see how Skippy has misled you -- and many others here.

    $rp = random_posts($catID, $count); won't work because $catID and $count are not declared. Hey Skippy, you need to change the directions here!

  55. Crys 2006-06-08 05:35:59

    Well I tried to make changes, but it's still not working. I'll just have to wait and see if anyone else makes a plugin/hack that does something similar to what I need it to do.

  56. heris 2006-07-06 15:01:25

    Great Plugin Skippy, I have tried it on WP 2.0.3. But why does the script also displays "about" link? Is it because I only have two posts so far? However, thank you very much for your great script.

  57. Moises Kirsch 2006-07-14 00:38:19

    Here is a tip when using this plugin...

    Instead of using get_the_title($p) and so on...

    Use setup_postdata($p) and after that you can use the regular template tags.

  58. Remco 2006-08-31 04:09:58

    Hi,
    I just wanted to let you know in the example code above (the code after: "then insert the following code in your template:"), you are missing a proper php closing tag. The question mark is not there.
    This might cause some of the errors people decribe here. Hope this helps! thanks for the plugin !
    Remco

  59. arlen 2006-11-12 00:13:29

    I got it to work a little too well. It finds not only posts, but also pages and even images. I really only want to give a link to one random post from any category; perhaps this plug-in, elegant as it is, is a bit overkill for my current uses.

  60. skippy 2006-11-12 08:50:33

    arlen: this plugin was written before WordPress had a notion of pages. Try changing line 23 to look like this:$sql .= " WHERE post_status='publish' ORDER BY ID ASC";and see if that produces better results.

  61. JH 2006-11-24 14:39:19

    Moises you said,

    "Here is a tip when using this plugin…

    Instead of using get_the_title($p) and so on…

    Use setup_postdata($p) and after that you can use the regular template tags."

    Can you please give an example how to implement this code? Thanks.

  62. JH 2006-11-24 15:46:34

    Is there a way to include the excerpt?

Leave a comment

Tags used: modification wordpress

a Flickr photoa Flickr photoa Flickr photo