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!




"You can see this hack in action right here." Dead link.
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?
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:
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.
I'm currently working on a hack to randomly delete stupid user comments.
I never dropped in to say thanks! :)
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?
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
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..
Emeric: it would help immensely if you could describe your problems.
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.
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
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.
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.
Steve: the code you tried to paste got lost. Try again, without the <?php and ?> tags, if possible.
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
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.
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.
Parse error: parse error, unexpected '>' in /home/shinesky/public_html/wewe/wp-content/themes/rin/sidebar.php on line 43
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?
Try
print_r($p)to see what the array contains. Then you can use$p['foo']to access the individual array elements.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
Thomas: The loop usually lives inside
index.php.So I put the code
";above the Loop in index.php?$rp = random_posts($catID, $count);
foreach ($rp as $p) {
$title = get_the_title($p);
$link = get_permalink($p);
echo "$title";
}
echo "";
>
Thomas: that should work.
heh heh, I love that word, "should". I'll keep trying.
I am getting an error using this code
";My error is:$rp = random_posts($catID, $count);
foreach ($rp as $p) {
$title = get_the_title($p);
$link = get_permalink($p);
echo "$title";
}
echo "";
>
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
kat, make sure you close the php argument
the last bit of code should be "?>" - not just ">"
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?
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.
Thanks! I'll let you know how it turns out!
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.
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
:~)
The invisible ink hid the <?php the_content(); ?>
Does using the random posts plugin trigger WP to ping every time new random post appear on your blog?
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?
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";
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?
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;... ususal standard loop thingies ...query_posts($query);
if (have_posts()) : while (have_posts()) : the_post(); ?>
I suppose there should be a better way (not a work-around like this) but that's for others to figure out :)
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;
}
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!
I added the ? and its now showing a random post link rather then the random post content
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.
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.
Works great in my Sidebar! (WP 2.0.2)
Awesome Plungin! Thanks a lot!
Greetz from Brazil, Dietmar
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? :)
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; ?>
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)] . "')";
}
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.
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.
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?
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; ?
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?
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.
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!
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.
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.
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.
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
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.
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.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.
Is there a way to include the excerpt?