Package/plugin/module WordPress

Plugin: Random File

This plugin has been updated! Comments to this post are now closed. For the latest download, documentation, and link for posting new comments related to this plugin, visit the plugin’s new homepage at:
Random File
Scott Reilly
Last updated:
25 March 2005

Retrieve the name of a randomly chosen file in a given directory. Useful for displaying random images/logos or including text from random files onto your site (writing excerpts, multi-line quotes, etc).


– If you want to actually display the name of the random file, be sure to ‘echo’ the results:
<?php echo c2c_random_file('/random'); ?>

– The directory of random files must exist at the directory structure level of your WordPress installation or below. (i.e., if your site is installed on your server at /usr/local/htdocs/yoursite/www/journal/, then the directory of random files you specified will assume that as its base… so $dir=’randomfiles’ would be assumed to actually be:

– $extensions can be a space-separated list of extensions (case insensitive), i.e. ‘jpg gif png jpeg’

– Unless you limit the file search to only include a particular $extension, all files in the specified $dir will be under consideration for random selection.

– The reference to the randomly selected file can be returned in one of four ways: ‘absolute’, ‘serverabsolute’, ‘url’, or ‘filename’

– Can be run inside or outside of “the loop.”

  1. Download the file and unzip it into your /wp-content/plugins/ directory.
    Copy and paste the the code ( random-file.phps ) into a file called random-file.php, and put that file into your /wp-content/plugins/ directory.
  2. Activate the plugin from your WordPress admin ‘Plugins’ page.
  3. Add a call to the function to your template (see examples below).

function c2c_random_file( $dir, $extensions='', $reftype='relative', $exclusions='' )

  • $dir : The directory of random files must exist at the directory structure level of your WordPress installation or below. (i.e., if your site is installed on your server at /usr/local/htdocs/yoursite/www/journal/, then the directory of random files you specified will assume that as its base… so $dir=’randomfiles’ would be assumed to actually be: /usr/local/htdocs/yoursite/www/journal/randomfiles/)

    Leading and trailing ‘/’ are unnecessary… ‘/randomfiles/’ == ‘/randomfiles’ == ‘randomfiles/’ == ‘randomfiles’

  • $extensions : space-separated list of extensions (case insensitive), i.e. ‘jpg gif png jpeg’

    Unless you limit the file search to only include a particular $extension, ALL files in
    the specified $dir will be under consideration for random selection

  • $reftype : The reference to the randomly selected file can be returned in one of three ways:
    [Assume your WordPress installation is at and you’ve
    invoked c2c_random_file(‘random/’, ‘txt’, $reftype)]

    $reftype = ‘absolute’
    => An absolute location relative to the primary domain:
    [This is the default setting as it is the most applicable. Absolute referencing is necessary if
    the random file is to be used as an argument to include() or virtual(). It’s also a valid way
    to reference a file for A HREF= and IMG SRC= linking.]

    $reftype = ‘serverabsolute’
    => An absolute location relative to the root of the server’s file system:

    $reftype = ‘url’
    => The URL of the random file:
    [If you desire the use of full URL, such as for a A HREF= or IMG SRC= link.]

    $reftype = ‘filename’
    => The filename of the random file:

  • $exclusions: optional; if specified it MUST be an array of filenames to exclude from consideration as a random file
Tips & Examples:

// Include random logo or image on your site:

<img alt="logo" class="logo" src="<?php echo c2c_random_file('/wp-content/images/logos/'); ?>" />

// Insert text from a random file (i.e. for random multi-line quotes):

<blockquote class='todayquote'> <?php virtual(c2c_random_file('/quotes/', 'txt')); ?> </blockquote>

// If you wanted to source a random .php file

<?php include(c2c_random_file('/randomphp', 'php')); ?>

// If you wanted to show three random (and different) images

<?php $files = array(); for ($i=1;$i<=3;$i++) { $file = c2c_random_file('/wp-content/images/', 'jpg png gif', 'url', $files); echo '<img src="' . $file . '" alt="Random image #' . $i . '" />'; $files[] = $file; } ?>

Release Log:
  • 25 Mar 2005 : v1.0 —
    • Renamed function from random_file() to c2c_random_file()
    • Added new reftype of ‘filename’
    • Added optional array argument $extensions for files not to be considered in random file selection
    • Updated license and examples
    • Verified that plugin works in WP 1.5 (and still works in WP 1.2)
  • 08 Jul 2004 : v0.9 — Released to the public
Copyright & Disclaimer:

Copyright (c) 2004-2005 by Scott Reilly (aka coffee2code)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.


I’d like to thank Matt Mullenweg, whose Random Image Script I came across after I was most of the way into making this plugin and which provoked a couple worthwhile considerations (among which was that I should support multiple extensions).

56 replies on “Plugin: Random File”

Sam: It can do either, depending on how you use it. If you just want to show the code as text (and not have that code evaluated), then use the virtual() function with the random file as the argument. For example:

<?php virtual(random_file('/code/', 'php')); ?>

Nice work, Scott. I tried to use it in a stylesheet but, for whatever reason, it didn’t work there. In the end I used an inline style to get it to load as a background image and all was right with the world. Thanks a lot for a great piece of code.

Could you set this up to pull several random files (like 5 or so) without any repeats? I’d like to have several randomly generated pictures on my site without doubling them.


Reload the page a few times… I’ve got random masthead images! 😀

Awesome! So many on the ‘net are trying to send a ‘random.php’ file as the CSS background image, but the key is to make some copies of your CSS and point each one to a differen…

Scott, I’ve been keeping an eye on your marathon work this past week, and have already put some of your plugins to use. Thanks! 🙂

I have a question about the random file plugin. What is it that causes the plugin to switch to another file? I refreshed my page a few times before the second file (one of two files) finally got quoted on the page. Is there a setting that I can modify to have it select a new file every ‘X’ times or something?

Thanks again!

I’m looking at several of the randomness plugins to try to do what I want. Assuming I use this one, I have these questions:

Is it possible to designate a prefix for files as well as extensions? This way, using in combo with Photopress (which puts full-size and thumbs in same folder), you could have the thumbnails display randomly.

Or could you code in a size limit option for images.

If there is a better way or a plugin that will pull a random thumbnail photo into the front page but outside the post, yet have the full size of the image in a post? Any ideas/instructions appreciated.

Following up on my last comment:

It’s easy enough to control the size right in the img tag, but if I could filter in only the files that start “_thumb” (or out those that don’t, I’m not picky), my life would be complete. From what little I know about php, it seems like this would be a simple argument to construct, to add to the plugin. Does anyone have any ideas how to do this?

My install is at at the moment, later to be /re

Great plugin. With Lazy-Galery I start to use it for publishing pictures. Is there any possibility to choose not random image, but just X newest? I now, then it will not be an Randomness plugin, but it will help me 🙂

An exceptionally useful plugin. Thanks 🙂

I have one bug and one feature request that would make it even more useful. First, the bug: ‘absolute’ returns the full path on the server (line 122):

return ABSPATH . $dir . $files[$rand];

…and related to that the source doesn’t account for ‘serverabsolute’ as an option. Should be easy to fix (or is the linked .zip an old version?)

Second, why not use $_SERVER['DOCUMENT_ROOT'] instead of ABSPATH since that would enable the plugin to retrieve random content from outside of the wordpress installation directory.

I for one would find that most useful, since I try to keep as much content as possible outside of the wordpress directory for easy upgrades.

Thanks again for a great plugin, and I hope that’s helpful.

So I want a simple random quote to be displayed: what do I use for a “call”?

I used the above examples with the correct directory and all I get is: “Call to undefined function: virtual() in…”

So i tried a bunch of other ways too…for now I just would like to see it work. Next I would like to take the code and have a ballon pop up on mouse over with a random quote in it. THis part will be easy if I can figure out how to get the quote.

Also do the txt pile need to be in a special format?

Thanks for helping out!

[…] A volte i cambiamenti che un autore applica al suo blog non sono visibili ‘in superficie’, soprattutto quando si tratta di migliorie funzionali al meccanismo di editing e pubblicazione. E’ il caso del nuovo plug-in che sto per adottare nella preparazione di questo blog: si chiama ‘Text replace‘ ed e’ l’equivalente di quelle che in gergo informatico vengono chiamate ‘macro’, ovvero sistemi per automatizzare determinate operazioni. Anzi, piu’ precisamente somiglia moltissimo al meccanismo di sostituzione automatica del testo che troviamo in Microsoft Word, e che aiuta a digitare parole o frasi di uso frequente associandole a una breve sequenza di caratteri, che una volta digitati sono automaticamente ‘tradotti’ nella parola o frase scelta. Nel caso del mio blog, visto che ancora adesso mi ritrovo quasi sempre a digitare carattere per carattere i tag HTML che aprono una pagina linkata in una nuova finestra oppure quelli che definiscono l’allineamento delle immagini rispetto al testo, credo che l’adozione di questo plug-in si rivelera’ una mano santa, come si suol dire. L’autore di Text Replace ha creato anche un plug-in piu’ evoluto, che si chiama Dynamic Text Replace e puo’ essere utilizzato, per esempio, per inserire automaticamente dei link che possono avere parametri diversi, come una ricerca di Google o un riferimento a un libro su Amazon. Inoltre, dello stesso autore, vi segnalo l’interessante Random File, che come dice il nome permette di inserire un file a caso scelto da una cartella sul server, per esempio per cambiare un’immagine all’interno dell’intestazione (come nel template Random Image che ho usato per l’altro mio blog MobTech). Un plug-in simile a questo e’ Random Witty Text, che come si capisce dal nome e’ specifico per l’inserimento di una porzione di testo prelevata a caso da un file, per esempio una citazione famosa o una barzelletta. Se volete approfondire l’argomento plug-in, ho inserito contestualmente a questo post anche qualche nuovo link nella sezione Blog World qui a fianco. Ah, ovviamente il titolo di questo post si riferiva al sito Cofee2Code, se c’e’ ancora qualcuno che si sta chiedendo cosa c’entra il caffe’ in tutto questo (a parte che si tratta della mia ‘droga’ quotidiana). […]

First, thanks for this plugin. It’s really cool.
Second, a litle question :
I have all my pictures in sub-folder to folder “Picture”.
At this time I can only return a random picture from a specific subfolder.
How can I do to hav a random on all pictures that are in my subfolder (subfolder are all under the folder “Picture” ???

Thanks for your help and keep up the good work 🙂

This is a much-appreciated plugin. Thanks for providing it.

It works well on my computer. But there is a problem with using it with the cgi version of php. Or so I’m told by the site5 customer service. I’m in process of migrating my site.

This is what they say:

“The layout is broken because you are using the virtual() php function, which is not supported in the cgi version of PHP, changing this to include() or require() would work.”

I tried changing a virtual to an include, but that did not work. Is there a way to use this excellent plugin under these circumstances?

Hi there,

Is there any way to convert this RANDOM FILE PHP file into either a C or Visual Basic code, so I can compile it into an EXE and run it in a Command Prompt on Windows?


Can anyone tell me why the line:
function c2c_random_file( $quotes, $txt=”, $reftype=’relative’, $exclusions=” )
now appears at the top of my webpage and on all the WordPress admin pages? The plugin is working though… is there something special I need to do when adding that line to the functions.php? can i only have one function in there?

Weehee, just dropped by to say thanks for the wonderful plugin!!!! After tinkering a bit (I’m a php noob) it works wonderfully and serves just the purpose I wanted..

Have a nice day,

I´m using this plugin, and is working fine, except when I include a php file, with images like in your array() example, the php file and images display ok, but the wordpress sidebar is gone! seems like get_sidebar() is not working. I looked the error log, but there is no error. ¿Anyone know what can cause this? ¿Maybe due to the array() or the for()?

From reading up on this script, I assume it would be easy enough to get the script to pick up a file/image from a specific table in mysql based on different categories and/or keywords?

For example, for the “HEALTH” category, i’d like the script to go and spit out a random file/image from a table created specifically for that category.

Any helpers?

[…] I hope you don’t mind I looked under your hood.. at your HTML source that is. I see that you are calling a PHP file as the header background. This works fine but consider this…. every time a person visits your page the the rotate.php sends an image. It could be a new one or the same one sent before… but every time it is sent. No caching. It is better to rotate the src text between different filenames and allow the user’s browser to cache each one. Then the users browser gets the image only if the image is new to them. Saves time and bandwidth… and with the large header images it can make a big difference. For my site I used […]

This is a great plugin and I use it extensively on one of my sites. However I’d like to use it on another site where I need 3 random (but not repeated) images presented horizontally rather than vertically. I’m sure this is possible with a simple change in the plugin’s code, but I don’t know PHP and have no clue how to make the change. Can anyone help? Please? Thanks.

Comments are closed.