This is the function to diplay random image from folder. You can use this function to display banner on your website as well as you can show galley image randomly just like other popular news websites. With little javascript tweak, you can also create slide show. It will cover this in my upcoming post.

Required Directory Permission
Image Folder: 555
Image Itself: 555

function get_random_image($image_dir)
Initialize variable

//get directory object
$img_obj = dir($image_dir);

//scan folder for allowed file extension
while ($f = $img_obj->read()) {
if (eregi(“gif”, $f) || eregi(“jpg”, $f) || eregi(“png”, $f))
$images .= “$f “;


//creating image array
$img_array = explode(” “, $images);
$num = sizeof($img_array)-2;

//generate a random number between 0 and the number of images
$random = mt_rand(0, $num);
$img = $img_array[$random];

//return image code
return “<img src='”.$image_dir.$img.”‘ border=’0’>”;

Written by Bala Krishna

Bala Krishna is web developer and occasional blogger from Bhopal, MP, India. He like to share idea, issue he face while working with the code.

This article has 2 comments

  1. Joshua Iz


    I’d like to incorporate this function within a function that adds some default avatars to WordPress comments. Ideally, I would like the function below to grab random images from a folder that I specify.

    I just don’t know enough PHP to get it working. Here is the avatar function:

    * add a default-gravatar to options
    if ( !function_exists(‘fb_addgravatar’) ) {
    function fb_addgravatar( $avatar_defaults ) {
    $myavatar = get_bloginfo(‘stylesheet_directory’) . ‘/images/vizual_avatar2.png’;
    $avatar_defaults[$myavatar] = ‘Vizual’;

    $myavatar2 = get_bloginfo(‘stylesheet_directory’) . ‘/images/basic_avatar.png’;
    $avatar_defaults[$myavatar2] = ‘Basic’;

    return $avatar_defaults;

    add_filter( ‘avatar_defaults’, ‘fb_addgravatar’ );

    This just adds two avatar options to the Settings > Discussion page and then grabs the image of the option you select. I would like for this function to grab a random image from a folder. Any ideas on how to do this?