Wordpress plugin: Random categories with random posts
November 14th, 2005
I’ve finally gone and done it, I wrote my first Wordpress plugin. Due to time constraints, lack of sleep, and wanting to be as descriptive as possible I’ve decided to call it Random categories with random posts, catchy isn’t it.
What prompted this fit of initiative? A simple request. Peter Flaschner from The Blog Studio needed some code that would hook into WP and display a random category. Simple enough, there are plugins that do that. The difference was that he needed to grab a number of random posts from that random category — which linked to their permanent place in the blog as well. Two days later I was finished.
This version is not compatible with Wordpress 2.3+ Please use this version.
The details
Usage
< ?php echo random_category_and_posts('display_type', 'element_before_heading', 'element_after_heading', number_of_posts, includeExcerpt, 'category_id', 'custom_field_name', 'custom_field_value'); ?>
-or if you would like to store it in a variable for later use-
< ?php $randPosts = random_category_and_posts('display_type', 'element_before_heading', 'element_after_heading', number_of_posts, includeExcerpt, 'category_id', 'custom_field_name', 'custom_field_value'); ?>
Note: When placing the code on your site, remember to remove the space between the ‘<’ and the question mark (?) from the above examples. Also, be sure to populate the code with the correct values (see below).
Parameters
- display_type
- (string) Determines how the random posts are displayed. Current options are
ulfor unordered list,pfor paragraphs [each post would be in it's own set of <p> tags], andbrfor one paragraph with a line break after each post. More options will be offered as development and suggestions continue. Default isul. - element_before_heading
- (string) Determines what HTML tag should be used to style the random category name. This value can include CSS classes provided the quotation marks are escaped in the function call [eg.,
random_category_and_posts("ul","h2 class=\"foo\","h2");]. Default ish2. - element_after_heading
- (string) Similar to the previous parameter, this is the value that should be in the closing HTML tag for the random category name. For example, if
h2was used in the previous parameter,h2should be used in this parameter. Default ish2. - number_of_posts
- (integer) Determines the number of posts to display. Default is
5. - includeExcerpt
- (boolean) Value to determine if the posts excerpt content should be shown in a
pelement following the post title. Default isFALSE. - category_id
- (integer) Will only search this category for random posts if a category is given. Default is
NULL. - custom_field_name
- (string) Specifies the name of the custom field the plugin should check for in the random posts. If not specified any post in the category choosen can be displayed. Default is blank.
- custom_field_value
- (string) Specifies the value of the custom field choosen in the previous parameter. For instance, if the custom field in the previous parameter was called “foo” and this parameter was set as “bar” only posts that contained the value “bar” in the “foo” field would be shown in the random list of posts. Default is blank
Version history
Version 0.5 — October 23, 2007
- Added
includeExcerptparameter to optionally allow showing the post’s excerpt content
Version 0.4.3 — March 23, 2007
- Made various adjustments to avoid potential conflicts with other plugins
Version 0.4 — January 18, 2007
- Set internal default values so if the plugin is called with all
nullvalues it will still display results - Only categories with at least one post will be shown
- Various code updates
Version 0.3 — March 25, 2006
- Updated compatibility for Wordpress 2.0
- Added option to specify category to pull random posts from
- Various minor code updates and code comments added
Version 0.2.5 — January 10, 2006
- Fixed bug with specifying custom fields
Version 0.2.3 — November 14, 2005
- Released to the public
Installation instructions
Installation is fairly straightforward, simply expand the downloaded file random-cat-with-rand-posts.php into the /wp-content/plugins/ directory. Load up your WP admin page in your browser of choice and activate the plugin.
Any suggestions or praise will be happily accepted in the comments of this post. If you have a question or bug report send me an email and we’ll get it sorted out.
On November 19th, 2005, Mike said:
Post updated to include installation instructions and place the download link earlier in the post.
On January 9th, 2006, stew said:
Just wondering if it’s possible to use this to display only photos from a random category that they belong to?
ie. A selection of photos are saved under the category “Photos,” and on the homepage you have your separate entry for text, category named “Text.” You want to display a random photo, while displaying your most recent entry of text.
On January 10th, 2006, Mike said:
Right now it will only display the post title and not the post contents. In the future I was looking at adding the ability to show excerpts or truncated content.
On March 13th, 2006, Steve said:
Would like to get a random post for a particular category. If you could extend your plugin to take a category parameter, that would be great.
On March 13th, 2006, Mike said:
Absolutely Steve. I’m looking to make an update in the near future. I’ll keep you informed.
On May 15th, 2006, John said:
I get Error, how to fix this problem…?
PHP Warning: Invalid argument supplied for foreach() in /home/sloki/user/xxx/sites/xxx.com/www/wp-content/plugins/random-cat-with-rand-posts.php on line 27
Warning: Invalid argument supplied for foreach() in /home/sloki/user/xxx/sites/xxx.com/www/wp-content/plugins/random-cat-with-rand-posts.php on line 27
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 'number_of_posts' at line 9]
SELECT wp_post2cat.post_id, wp_post2cat.category_id, wp_posts.ID, wp_posts.post_title, wp_postmeta.post_id, wp_postmeta.meta_key, wp_postmeta.meta_value FROM wp_post2cat, wp_posts, wp_postmeta WHERE wp_post2cat.category_id = ” AND wp_posts.ID = wp_post2cat.post_id AND wp_posts.post_status = ‘publish’ AND wp_postmeta.meta_key = ‘custom_field_name’ AND wp_postmeta.meta_value = ‘custom_field_value’ AND wp_postmeta.post_id = wp_posts.ID ORDER BY RAND() LIMIT number_of_posts
On May 15th, 2006, Mike said:
John: It looks as though there is no integer/number being supplied for the
$numPostsvariable. How are you calling the function in your blog?On May 15th, 2006, John said:
Mike: I’m calling from sidebar.php
What’s wrong?
On August 31st, 2006, Remco said:
Thanks for this plugin, exactly what I needed!
On August 31st, 2006, Mike said:
Glad you like it Remco.
On September 18th, 2006, Trevor Turk said:
Awesome. Very flexible and lightweight. This is going to solve a lot of my problems real quick. Thanks!
On September 18th, 2006, Mike said:
Thanks Trevor, happy to hear that it’s going to help you.
On October 25th, 2006, miklb said:
Could you help me output the content or excerpt as well?
On October 27th, 2006, Mike said:
miklb: email sent.
On October 31st, 2006, miklb said:
Thanks, but I had a typo in my email. Another shot?
On January 14th, 2007, Felix said:
Hello Mike!
Nice PlugIn. I have the following suggestions for a little improvement
- if no category is choosen (random cat is activ), the PlugIn should try to deliver everytime a link to a post. At the moment it is possible to receive no link if the random cat is an empty one: “currently no entries in this cat”.
- it should be possible to retrieve links without any format outputs. if i call the function this way: random_category_and_posts(”,”,”,3,null,”,”) i get ” Posttitle”.
Best regards
Thanks
On January 18th, 2007, David said:
First: Thanks for that great plugin. Works fine and is exactly what I was looking for. The only problem I got is that it chooses the unsorted-category from time to time. Is there a way to exclude it? Thanks!
David
On January 18th, 2007, David said:
Is it possible to insert a class-attribute in the ul-tag?
On January 18th, 2007, Mike said:
Felix, both of your suggestions have been implemented in version 0.4. Now if no values are given to the plugin they will display with the default
h2for the title and the posts will be a list of links.Also, the plugin now checks to make sure there is at least one post in the random category. No longer will you see the dreaded “currently no entries in this catâ€.
David, at this point there is no functionality to exclude categories. I’m not sure if or when I may have time to add it. Unfortunately same goes for adding attributes, though attributes would be a great addition.
On January 24th, 2007, David said:
Another question after I used the script for a while on http://www.bittekunst.de: It would be great to link to the specific category you take the posts from. Is there a possibility to?
Thanks for your work, Mike. I appreciate that.
David
On January 24th, 2007, Mike said:
David, I’ll see what I can do.
On January 25th, 2007, Tekiela said:
THANK YOU SO MUCH for this super-nice PLUG!
works like a charm!
my question is basically the same as miklb said:
Could you help me output the content or excerpt as well?
I really need the excerpt is there a workaround?
thanks thanks thanks
jacob
On January 25th, 2007, Zurevla said:
Thanks for your work on this plugin.
I just got it installed and running on http://zurevla.nl
On February 18th, 2007, Jeffrey said:
Great plug in, is there a way to seperate my posts. When it calls the posts it puts them in a list. This is how I am calling them:
Then the reponce I get is:
Age Group
Contact MeWater GamesNight GamesWind Surfing5-7 Years all
I am wondering how to get it to look like this:
Age Group
Contact Me
Water Games
Night Games
Wind Surfing
5-7 Years all
where each post has it’s own line so that it is earier to see the individual posts. To see the site it is just starting so I am in testing stages still but the site is http://www.mycampresources.com
Thanks
Jeffrey Penner
[Editor—Jeffrey and I worked this out via email and the plugin is now working fantastically on his website]
On February 26th, 2007, _ck_ said:
Hmm, do you have a demo running on your blog here?
Am I understanding correctly what this might do for me - I’d like a category called “Random” added to my cat list on the sidebar and then when I click it, it shows a page of random posts from across the blog?
I guess I’ll download it and give it a go to see…
ps. I like your blog css & layout, nice and clean…
On February 26th, 2007, Mike said:
_ck_, I don’t have a demo on this blog but if you check out http://www.mycampresources.com/ and look at the right sidebar under “Games” and reload the page you’ll see how it works.
That particular example only pulls posts from one category but the plugin can actually pull from random categories that have at least one post as well.
The way you’re describing your understanding is possible but it would have to be a “random” page that you created instead of a “random” category. Then you could call the plugin from the page.php template using some conditional calls (ie.,
if ( is_page('random') ) : random_category_and_posts(); endif;).If you have any other questions let me know either via comment or email.
Thanks for the kind words about the site.
On February 26th, 2007, _ck_ said:
Oh! I see what you mean. Make a page and hook the random posts code in the general index.php. Clever.
I think it’s exactly what I want. It’s a nice feature if you have alot of posts and want to encourage people to random sampling of all your work over time (which they usually don’t have the patience to browse the entire site)
Too bad we can’t (easily) trick wordpress into actually creating a physical category called “Random” so it will be in the cat list if listed in the sidebar. On second thought, that might actually be possible 7if I catch it in the template’s index.php (like you suggested) and tell it to use your plugin! Going to give a try tonight…
ps. one thing I can suggest right off to enhance your plugin would be stronger ways to specify multiple categories ie.
include (5, 7, 9, 4)
which would only select from those categories
or
exclude (6, 2)
which would use all categories except those two
more later after I’ve played with it a bit…
On February 26th, 2007, Mike said:
Yeah, after the initial release of this plugin I started to see how useful it can be to do just that, point out content that otherwise might not be seen by the casual visitor.
As far as tricking WP into getting an actually random category, that could be possible via a plugin but it would take some investigation.
Including and excluding categories has been brought up before. I’ve been looking into it but the workload is a bit of a hinderance at the moment. I’ll definitely be included in the next major version though.
On March 23rd, 2007, jeremy clarke said:
Hey man, I think there’s a bug in the currently posted version of the plugin that’s breaking the ability to set a specific category rather than having a random one generated.
in the random_category function at line 69
if ( $ms_catID ) $sql .= " AND cat_ID = '$ms_catID'";Should be:
if ( $ms_catID ) $ms_sql .= " AND cat_ID = '$ms_catID'";As it is now the AND just falls into the void of the inactive $sql variable (boy was that frustrating ;)
Thanks for the plugin, keep up the good work.
On March 23rd, 2007, Mike said:
Thanks Jeremy for catching that. I was hoping I found and changed all of those variables but apparently I didn’t. I’ve made the change and have updated the file on the server.
Anyone that downloaded the previous version please update to 0.4.3. Thanks.
On April 15th, 2007, shan said:
Thank you for this plugin! This is exactly what I need, works very nicely!
On June 19th, 2007, Dan said:
Hey, nice plugin, would it be possible to get some details on displaying the content/excerpt with the post title? Thanks.
On June 24th, 2007, Webkoktejl said:
Hi, I think, this is the best “random plugin” a found. Thank you for that.
On June 25th, 2007, franck said:
Hi Mike,
i had this error when i installed the plugin and lunched my site in the browser,how can i fix it please? Actually the MySQL version is 5.0.
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 wp_post2cat.post_id, wp_post2cat.category_id, wp_posts.ID, wp_posts.post_title FROM wp_post2cat, wp_posts WHERE wp_post2cat.category_id = ” AND wp_posts.ID = wp_post2cat.post_id AND wp_posts.post_status = ‘publish’ ORDER BY RAND() LIMIT
Also thank you for this plugin.
On July 24th, 2007, akisok2 said:
On January 24th, 2007, David said: “It would be great to link to the specific category you take the posts from. Is there a possibility to?”
Has anyone been able to make this happen? I have been experimenting with the plugin to get this function, but with no luck.
Any suggestions?
On July 31st, 2007, Leanne said:
Hi Mike,
Your plugin appears to be what I’m looking for - but I’m not seeing any updates regarding the excerpt/content pulling in with the randomness. Have you had a chance to add that feature?
Thank you!
On August 16th, 2007, Bloody said:
Mike,
I’ve got the same problem as franck.
My website is Wordpress 2.2. Maybe a plugin update ? :)
On August 18th, 2007, Mike said:
@Bloody: The problem in franck’s comment was that he was missing a variable in his call to the plugin. As long as all the variables listed in the “Parameters” section of this post are filled in correctly you shouldn’t have any problems. If you try a few things and still can’t get it working, comment with how you call the plugin (without the
< ?phppart).@Leanne: I haven’t had the opportunity to add the links or excerpt/content to this plugin. To be totally honest, I don’t know when that might happen, work has been a little hectic.
On September 3rd, 2007, Karimun said:
Mike:
I want your plugin no to include the first 5 posts in the given category.
The reason is that I want the first five posts listed chronologically by the loop and your plugin should now randomly display post from the remaining ones. I tried to implement “&offset=5″ in different places of your code and produced only errors.
Thanks for this plugin.
On October 6th, 2007, marcos said:
I hope you can make an update so the plugin can be compatible with Wordpress 2.3
Here’s the error:
WordPress database error: [Table 'explorei_primary.wp_categories' doesn't exist]
SELECT cat_ID, cat_name, category_count FROM wp_categories WHERE category_count >= ‘1′ AND cat_ID = ‘82′ ORDER BY RAND() LIMIT 1
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 wp_post2cat.post_id, wp_post2cat.category_id, wp_posts.ID, wp_posts.post_title FROM wp_post2cat, wp_posts WHERE wp_post2cat.category_id = ” AND wp_posts.ID = wp_post2cat.post_id AND wp_posts.post_status = ‘publish’ ORDER BY RAND() LIMIT
On October 13th, 2007, Speed DARYL said:
Hello,
Is it possible to know what to change to have the contents showing up ?
I managed to show all the content of an article, but i don’t understand how the excerpt thing works
thanks for all !!
On October 22nd, 2007, naturegirl said:
This is a great plugin, exactly what I needed. However, is there a way that I can show this widget multiple times on my side, each one for a different category? I tried copying the plugin file and changing the function names and playing around a bit, but I didn’t really get it nor do I understand a lot about php. Maybe you can give me some advice?
Thanks in advance and great plugin again!
On October 25th, 2007, weston deboer said:
Hi just found your plugin from weblog tools collection, it would be great if this plugin works for wordpress 2.3!
On October 31st, 2007, blogjunkie said:
Hi Mike! Yes, I would also love it if you could update the plugin for WP2.3. Thanks
On November 2nd, 2007, naturegirl said:
I’m using this plugin with WP 2.3. It does work…
On November 8th, 2007, Tyler said:
Hey Mike,
I seem to be getting the same type of error as “marcos” on October 6th, 2007. Is there a fix for this? Or do we have to wait for a new release?
I’m using this code:
And here’s the resulting error:
WordPress database error: [Table 'alronhauser.wp_categories' doesn't exist]
SELECT cat_ID, cat_name, category_count FROM wp_categories WHERE category_count >= ‘1′ AND cat_ID = ‘1′ ORDER BY RAND() LIMIT 1
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 wp_post2cat.post_id, wp_post2cat.category_id, wp_posts.ID, wp_posts.post_title, wp_posts.post_excerpt, wp_postmeta.post_id, wp_postmeta.meta_key, wp_postmeta.meta_value FROM wp_post2cat, wp_posts, wp_postmeta WHERE wp_post2cat.category_id = ” AND wp_posts.ID = wp_post2cat.post_id AND wp_posts.post_status = ‘publish’ AND wp_postmeta.meta_key = ‘ ‘ AND wp_postmeta.meta_value = ‘ ‘ AND wp_postmeta.post_id = wp_posts.ID ORDER BY RAND() LIMIT
Thanks,
Tyler
On November 8th, 2007, Mike said:
To all: Any database errors that have the text “.wp_categories” in the error message is an incompatibility with Wordpress 2.3. There was a database change that killed the wp_categories database and replaced it with a terms database.
I’ll be hitting the bricks tonight to finish off the updated version and will post it as soon as possible. I do have a working 2.3 compatible version but as I was looking through the code I decided a total rewrite was due (as well as some slightly new functionality).
So, stay tuned and check back in the next couple days for the new plugin (it may have a new name and a new blog entry for clarity).
On November 8th, 2007, Tyler said:
Cool, thanks for the update Mike!
On November 10th, 2007, Mike said:
I’ve finally made the long awaiting 2.3 update. Due to the full code rewrite I’ve moved it to it’s project page.
The update is only compatible with Wordpress 2.3 and up, so I’ll be keeping this plugin as it is for those that don’t or haven’t upgraded yet.
On November 10th, 2007, Tyler said:
Mike,
So I’ve installed version 0.6 and I’m getting this error when I try to specify $ms_term_id as ‘27′. I want only posts from category ID 27.
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 'wp_terms.term_id = '27' ORDER BY RAND() LIMIT 1' at line 1]
SELECT wp_terms.term_id, wp_terms.name, wp_terms.slug, wp_term_taxonomy.count, wp_term_taxonomy.term_id FROM wp_terms, wp_term_taxonomy WHERE wp_term_taxonomy.count >= ‘1′ AND wp_terms.term_id = wp_term_taxonomy.term_idAND wp_terms.term_id = ‘27′ ORDER BY RAND() LIMIT 1
It’s fine when I don’t specify anything for that parameter but it seems to pull posts from my tags, not from my categories. Is that what you mean by “term”?
How can I get random posts with excerpts from just one category?
Thanks,
Tyler
On November 13th, 2007, Brian "doctabu" Moore said:
Oh man. If only you gave the ability to exclude categories, this would be absolutely perfect.
On November 13th, 2007, weston deboer said:
Yes i also would like to know how $ms_term_id works
On November 13th, 2007, weston deboer said:
Awesome developments! I notice that the ms random posts isn’t quite finished yet, but awesome thought, keep up the good work
On November 13th, 2007, Mike said:
Tyler & Weston: Turns out it was a minor snafu in my code that caused the MySQL error when specifying a category/term. If you download version 0.7 specifying just one category to show will work.
Brian: I’ve added the ability to exclude categories/terms with version 0.7, enjoy!
Tyler, again: In WP 2.3 the terminology of “categories” was depreciated, meaning the classification system being used is now called “terms”. This applies to both the built in tags as well as what used to be called “categories”. I tried to use both terms, category and term, in my explanations but I may not have done that all the time. Basically terms and categories are interchangeable until everyone gets comfortable with the new taxonomy structure. Hope this explanation helps.
For further discussion on versions 0.6 and up, please use this post from now on. Thank you.
On December 8th, 2007, Petra said:
Thank you very much for this plugin. I hope I will use it soon :)
On February 2nd, 2008, yosax said:
I’ve got this error message when using the plugin:
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 ' .name, .slug, .count, .term_id FROM , WHERE .count >= '1' AND .term_id = .term' at line 1]
SELECT .term_id, .name, .slug, .count, .term_id FROM , WHERE .count >= ‘1′ AND .term_id = .term_id ORDER BY RAND() LIMIT 1
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 ' .term_taxonomy_id, .term_id, wp_posts.ID, wp_posts.post_title FROM wp_posts, , ' at line 1]
SELECT .object_id, .term_taxonomy_id, .term_id, wp_posts.ID, wp_posts.post_title FROM wp_posts, , WHERE .term_id = ” AND wp_posts.post_status = ‘publish’ AND wp_posts.ID = .object_id AND .term_taxonomy_id = .term_taxonomy_id ORDER BY RAND() LIMIT 5
How to fix that?
On February 28th, 2008, Airdave said:
echo random_category_and_posts(”,’li’,'li’,9,null,”,”)
this is my string, but don’t word.
i’m use wp 2.3.3
what’s the solution?
sorry for my english
On February 28th, 2008, Mike said:
Airdave: This version isn’t compatible with WP 2.3+, please download this version.
On June 11th, 2008, dr801 said:
the link is not working “http://screenflicker.com/projects/random-plugin/”
any new links?
On July 26th, 2008, Mike said:
dr801: Fixed the link in my previous comment. Should have been screenflicker.com/projects/plugin-random/
On February 17th, 2009, Bill said:
This plugin is genius. Works perfectly on 2.7.1
I needed a plugin that allows me to post random posts from a category including custom fields and title that links to the post. This works so well, thanks!!!
On February 17th, 2009, Mike said:
Bill: Thanks! Glad you like it!