Tech Archives, page 30

All things technology. Very popular here on Justinsomnia.

Random Image plugin for WordPress

The latest version is 5.0, released June 20, 2008, now with support for WordPress 2.5 galleries, and still backwards compatible with 2.3, 2.2, 2.1, and 1.5

Inspiration

WordPress logoOne of the things I’ve been thinking about more since starting at O’Reilly is how to draw attention to a back catalog of content. For a single blogger, it’s pretty easy to link back to a relevant old post because of the information retrieval processor built into our heads. But for a site managed by an editor who may not be as familiar with the back catalog, the older content will languish, accessible only by search engines.

Then the other day I discovered the most amazing thing. I was freshening up the layout of O’Reilly’s Mac DevCenter, and we decided it would be cool to have a randomly populated book sidebar. Which meant I needed to pull records out of our database in random order—not something I’d ever needed to do before. It turns out that the SQL needed to do this is astoundingly simple:

SELECT * 
FROM table
ORDER BY RAND();

Maybe you only want a single random record? Easy.

SELECT * 
FROM table
ORDER BY RAND()
LIMIT 1;

Seeing this in action for the first time is like a revelation.

What does this plugin do?

Since I started blogging, I’ve added 500+ images to my blog posts, and I’ve always wanted some way to index them, or make them accessible in aggregate. I wrote a script once that generated a webpage to display all the images, but I had no means (at the time) to link them back to their associated blog posts.

Of course since I moved to WordPress, I have complete control over my content, so I decided to write a plugin to look for blog posts with images and return one image at random, linking back to its post. Update: If you prefer, you can now configure this plugin to display images in reverse chronological order (most recent to least recent) rather than in random order.

You can see it in action in the upper-righthand corner of my homepage. Here’s a screenshot:

randomimage plugin for WordPress screenshot

What doesn’t this plugin do?

This plugin does not rotate randomly through a group of images stored in a single directory on your webserver. If you are looking for a plugin to do that, try Matt Mullenweg’s A Rotater Apart or Kamiel Martinet’s WordPress random header plugin or MHough’s Header Image Rotator.

This plugin does not natively resize images (you can use the CSS on the optional image attribute parameter to resize the image in the browser). Which means it does not create thumbnails, create square thumbnail images, nor have any knowledge of how or where your WordPress-generated thumbnail images are stored. It simply looks for a random image that you’ve embedded in the content of your post (or gallery) and returns it. This ensures that it always correctly returns an image that actually exists.

Instructions

  1. Download and unzip randomimage-5.0.zip (v5.0)
  2. Upload the file randomimage.php to your plugins directory:

    /path/to/wordpress/wp-content/plugins

  3. Activate the plugin (don’t forget!)
  4. Edit the theme template file index.php or sidebar.php in your theme’s directory:

    /path/to/wordpress/wp-content/themes/name-of-theme

  5. Add the following line of code where you want a random image to appear:

    <?php randomimage(); ?>

  6. Configure the plugin from within WordPress under Options > Random Image
Random Image plugin for WordPress' configuration interface
Screenshot of the configuration interface (new in v2.0)

How to Include Random Images across Blogs

People have often asked, “How do I include a random image in my main blog from my other WordPress blog?” Actually it turns out to be very easy.

  1. First, randomimage.php must be installed as described above
  2. Download and unzip randomimage-standalone-1.0.zip (v1.0)
  3. Upload the file randomimage-standalone.php to your plugins directory (alongside randomimage.php):

    /path/to/wordpress/wp-content/plugins
    Note: This is not a separate plugin, it’s simply a supporting file for randomimage.php, therefore there is nothing you need to activate or configure.

  4. On the other blog (or any website, really) where you want the random image to appear, insert the following HTML snippet, replacing example.com/wordpress with the domain name (and directory, if any) where randomimage-standalone.php lives
    <script type="text/javascript" src="http://example.com/wordpress/wp-content/plugins/randomimage-standalone.php"></script>

    Note: for the random image to be appear, JavaScript much be enabled in the browser.

Options

The randomimage function can take 12 optional parameters in between the parentheses. If you specify any parameters this way, all settings made through the configuration interface (shown above) will be ignored. Note: this behavior could be useful if you wanted to have several different random images each with different settings appearing throughout your site.

<?php randomimage(show_post_title, 
                  number_of_images, 
                  image_attributes, 
                  show_alt_caption, 
                  image_src_regex,
                  post_type,
                  inter_post_html,
                  category_filter,
                  sort_images_randomly,
                  image_class_match,
                  image_template_html,
                  show_images_in_galleries); ?>
  1. show_post_title is a boolean (true or false) that determines whether the title of the original blog post is printed above the image. The default is true.
  2. number_of_images is an integer that determines how many random images the function should return. The default is 1.
  3. image_attributes is a string that gets inserted in the img tag which you can use to set attributes like a standard width or a title (tooltip). The default is an empty string. For example, "width='200'" would reduce the size of the image to be 200 pixels wide (and proportionally high).
  4. show_alt_caption is a boolean (true or false) that determines whether the alt attribute (if there is one) is printed below the image. The default is true. (new in v1.2)
  5. image_src_regex is a string containing a regular expression (without slashes) that matches against the image src attribute. For example, if you only wanted to display jpg’s and png’s, you would use "(\.jpg|\.jpeg|\.png)". If you only wanted to display images from a specific directory called images, you could use "images". This parameter uses the preg_match php function in case-insensitive mode. For more information on constructing regular expressions, check out regular-expressions.info. (new in v1.2)
  6. post_type is a string that allows the following three values: posts for including images from post content only, pages for including images from page content only, and both for including images from posts and pages. The default is posts only. (new in v1.3)
  7. inter_post_html is a string (presumably HTML) that is outputted between subsequent images if number_of_images is greater than 1. The default is <br /><br />. (new in v1.4)
  8. category_filter is a comma-separated value string of numerical category IDs that will limit the plugin to grabbing images from posts assigned to only those categories. The category IDs can be determined by going to Manage > Categories. The default is an empty string which will allow images from posts assigned to any category. (new in v2.1) Even though the name hasn’t changed, this option now includes tags too! (new in v4.1)
  9. sort_images_randomly is a boolean (true or false) that determines whether the image (or images) pulled from the database are displayed randomly or in reverse chronological order. By setting this option to false, the plugin effectively displays recent images, rather than random images. The default is true. (new in v3.0)
  10. image_class_match is a string that you can use to specify a classname that the randomly chosen image’s class attribute must contain. So if you set it to randomimage, only images with class="randomimage" (or even class="left randomimage") will be displayed. (new in v4.0)
  11. image_template_html is a string that acts as a template for displaying the image. With it you can create wrapper HTML around the image, or position the caption on top, or a myriad other things this plugin author hasn’t conceived. Use %1 in the template to represent the title, %2 to represent the image, %3 to represent the caption, and %4 to represent the post excerpt. By default, the template is:
    <strong>%1</strong><br />
    %2<br />
    <em>%3</em>

    Note: If image_template_html is specified, it overrides show_post_title and show_alt_caption. (new in v4.0)

  12. show_images_in_galleries is a boolean (true or false) that determines whether the plugin should show images from WordPress 2.5’s new gallery feature. The default is true. (new in v5.0)

If you wanted to use all the options together, you might add the following to your index.php or sidebar.php file:

<?php randomimage(true, 
                  1, 
                  "width='200'", 
                  true, 
                  "(\.jpg|\.jpeg|\.png)",
                  "both",
                  "<hr />",
                  "2,5,8",
                  true,
                  "randomimage",
                  "%3<br />%2<br />%1",
                  false); ?>

Development Ideas

Questions, comments, and suggestions are always welcome. If you’re interested in contributing to the code behind the Random Image plugin, it’s hosted on GitHub.

Firefox tip of the day: Delete saved form entries

Asa Dotzler at OSCONScenario: as your webmail login interface is loading, you’ve already selected your username—thanks to Firefox’s form autocompletion—but at the instant you tab over to the password field, the page finishes loading, some javascript onload event fires, and the page focuses the caret back in the username field.

Of course you’re not even looking at the screen because you do this so often, and before you realize it, you’ve hit enter and sent your username and your password together in the username field, which Firefox has just cached for all of eternity. Now the next time you go log in, Firefox’s autocompletion options exposes your password. Argh!

Solution: This shouldn’t be a big deal to fix, except the only UI option for clearing out a saved form value (that I can determine) is by going to Tools > Options > Privacy > Saved Form Information and selecting “Clear”. So it appeared to be an all or nothing proposition.

Well at least until I talked with Asa Dotzler at FOO Camp on Sunday. After a really nice long conversation, I thought to ask about why I couldn’t selectively remove saved form values and he said:

“Sure you can, it’s Shift+Delete.”

And sure enough it works like a charm. Thanks Asa.

The Web 2.0 Drinking Game

This idea was inspired by blatantly stolen from Greg McCarroll and James Duncan of Fotango at this year’s FOO Camp. It’s particularly lively among geeks with alcohol.

When someone says…

Any suggestions? Additions?

FOO Camp

As the story goes, someone was joking that O’Reilly should have a literal “foo bar” (see metasyntactic variable if you don’t get the joke) and invite movers and shakers in technology over for drinks. Thus FOO Camp was born, with FOO later becoming a backronym for “friends of O’Reilly.” Gee, all we need now is a Web 2.0 Drinking Game!

The Foo Bar at O'Reilly's FOO Camp 2005
The “foo bar” at FOO Camp 2005

So who are the tech superstars here that I know? (By “know” I mean “recognize”.)

The Bloglines guy. The Amazon guy. The del.icio.us guy. The Wikipedia guy. The Perl guy. The Atom guys. The Python guy. The Flickr folks. The Firefox folks. The Adaptive Path folks. The Smart Mobs guy. The We the Media guy. The Hackers and Crypto guy. The Yahoo guy. The Greasemonkey guy. The Technorati guys. The wiki guy. The BitTorrent guy. The Blogger and Odeo guy.

It’s kind of like OSCON, but with drinking during the conference and camping after. I hung out with the Knoppix Hacks guy (and friend), as well as some other O’Reilly folks. We played with a homemade Segway and drooled over the SUV of Segways that the Make magazine guy had brought.

After a while it was late, I was tired, and I was not going to be spending the night in a tent because I have a bed in Santa Rosa. Though I admit they looked pretty cool under the moonlight and fog in the orchard behind O’Reilly Media.

O'Reilly's FOO Camp 2005 night shot
Foggy moonlight hangs over the FOO Campers

Tomorrow I have a Beer Revival to attend, with a slim chance I’ll make it back in the AM to listen to some of the morning talks.

Google Maps, I salute you!

Every once and a while I feel like I’ve got to give serious props to the algorithms that play an active roll in my daily life.

In this case, I exhibit the Wilfred Avenue exit off of the 101 in Rohnert Park. If you find yourself heading south on the 101 (as I did tonight) and need to go east on Golf Course Drive, then your route will look like this.

Wilfred Avenue exit off of US highway 101