I'm trying to load a random image from my child them images directory each time the page loads.

I'm loading it as a shortcode right now. This is the code i'm using:

function footer_image () {
   $imagesDir = get_stylesheet_directory_uri().'/images/footer/';
   $imagespec =  get_stylesheet_directory_uri().'/images/footer/footer-fishing.png'; //for testing

   $images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

   $randomImage = $images[array_rand($images)].'there';

   return $randomImage;//this returns nothing.
   return $imagespec; //this returns the correct url for the image
   return $imagesDir; //this returns the correct url for the images directory
add_shortcode ('footer-image', 'footer_image');

in the end I want to use return $randomImage, but in my testing i've commented out that line and individually added each of the other returns to see if they are working. They both do.

So it would appear I have something wrong with the $images or $randomImage variable.

  • If you’re not sure about $images’ then pump it into your display with print_r()` or something like that so you can see what it has stored. In the $randomImage declaration array_rand() can return more than one value unless you set the second parameter to 1. Also adding the string ‘there’ onto the end of $randomImage looks like it might be a mistake. – Ben HartLenn Jan 19 '18 at 19:37
  • i'll try print_r(), the "there" was just to see if anything was coming out at all. – rudtek Jan 19 '18 at 20:06

Try to see if this works, I used scandir because I prefer it. The problem was that glob, like scandir, only works with paths on the server's file system, not URLs:

function footer_image(){

    $imagesDir = get_stylesheet_directory() . '/images/footer';

    $imagesUri = get_stylesheet_directory_uri() . '/images/footer/';

    $images = array_diff( scandir( $imagesDir, 1 ), array( '.', '..' ) );

    $randomImage = $images[ array_rand( $images ) ];

    $footerImage = '<img src="' . $imagesUri . $randomImage . '" alt="Footer image">';

    return $footerImage;
add_shortcode ( 'footer-image', 'footer_image' );

To use a shortcode in a page/theme template:

echo do_shortcode("[footer-image]");

P.S. Instead, if you created a taxonomy in the media library for example footer and took those images, you could use more attributes (alt, description, size, etc.), improve SEO and make the website more responsive. What do you think about it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.