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

Here’s a screenshot of the configuration interface (new in v2.0).
Random Image plugin for WordPress' configuration interface

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

  • Suppress printing caption if it’s the same as the image filename
  • Check image dimensions to prevent enlarging small images (?)
  • Add option to only display images within a certain width/height range
  • Add a check to make sure image exists
  • Optionally create a thumbnail of configurable dimensions (hard)
  • Store post image info in the postmeta table (hard)

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.

Feel free to if you found this useful.