Random Posts

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!


62 Responses to Random Posts

  1. 163 Bob 2004-05-28 12:04:03

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

  2. 167 Adam M. 2004-06-02 00: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. 168 skippy 2004-06-02 01: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. 179 Elfboy 2004-06-08 18:47:29

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

  5. 195 Sushubh 2004-07-20 01:51:19

    I never dropped in to say thanks! :)

  6. 307 Andrea 2005-01-13 13: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. 308 skippy 2005-01-13 14: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. 1212 Emeric 2005-07-26 13: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. 1216 skippy 2005-07-26 23:54:54

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

  10. 1430 Dave Addey 2005-08-26 12: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. 1462 Kevin 2005-09-01 17: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. 1461 skippy 2005-09-01 17: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. 1533 Steve Lambert 2005-09-12 06: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. 1538 skippy 2005-09-12 13:48:10

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

  15. 1540 Steve Lambert 2005-09-12 19: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. 1541 skippy 2005-09-12 19: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. 1549 Steve Lambert 2005-09-13 00: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. 1685 wewe 2005-10-08 02:17:33

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

  19. 1803 heatheer 2005-10-27 17: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. 1834 skippy 2005-10-29 12: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. 1848 Thomas 2005-11-05 05: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. 1849 skippy 2005-11-05 12:02:46

    Thomas: The loop usually lives inside index.php.

  23. 1851 Thomas 2005-11-05 15: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. 1852 skippy 2005-11-06 18:56:44

    Thomas: that should work.

  25. 1899 Thomas 2005-11-07 00:42:18

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

  26. 2351 kat 2006-01-09 16: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. 2463 at 2006-01-15 07:40:47

    kat, make sure you close the php argument

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

  28. 2510 MW 2006-01-22 07: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. 2505 skippy 2006-01-23 00: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. 2662 MW 2006-01-24 13: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. 2585 Onn 2006-01-30 18: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. 2581 Fred Crowson 2006-02-02 21: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. 2582 Fred Crowson 2006-02-02 21:20:34

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

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

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

  35. 2941 Sachin Garg 2006-03-05 23: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. 2944 Sachin Garg 2006-03-06 20: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. 2964 Sal Just Sal 2006-03-12 22: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. 2995 Ravan 2006-03-16 23: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. 2996 Ravan 2006-03-16 23: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. 3110 SavedScenes 2006-03-28 21: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. 3119 SavedScenes 2006-03-29 03:06:53

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

  42. 3257 Orbitalz 2006-04-25 21: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. 3258 Orbitalz 2006-04-25 22: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. 3259 Dietmar 2006-04-26 19:25:41

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

    Greetz from Brazil, Dietmar

  45. 3155 Crys 2006-05-10 10: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. 3156 Crys 2006-05-10 11: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. 3335 Geoff 2006-05-16 17: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. 3340 Geoff 2006-05-16 17: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. 3372 Crys 2006-05-20 17: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. 3368 Geoff 2006-05-24 07: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. 3300 Crys 2006-05-27 08: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. 3360 Forest 2006-05-27 23: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. 3299 Geoff 2006-05-28 20: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. 3306 Geoff 2006-05-28 20: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. 3348 Crys 2006-06-08 09: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. 3433 heris 2006-07-06 19: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. 3310 Moises Kirsch 2006-07-14 04: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. 3540 Remco 2006-08-31 08: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. 3466 arlen 2006-11-12 05: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. 3468 skippy 2006-11-12 13: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. 3443 JH 2006-11-24 19: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. 3444 JH 2006-11-24 20:46:34

    Is there a way to include the excerpt?

Leave a Reply



About

Brewer philosopher.

User