WordPress loading all local images from specific directory?

The question:

I need to load some local images..
I used this code before to load some images

        <?php 
        function loopImages(){
            $imagePath = get_stylesheet_directory()."/IMAGES/sponsors/";
            $filesList =glob($imagePath.'*.{JPG,jpg,PNG,png}', GLOB_BRACE);
            echo $filesList;
            foreach($filesList as $file){
                echo '<img src="'.$file.'">';
            }
        }
        loopImages();
    ?>

This worked almost fine. I could loop through files and browser could render 8 img tags, but it showed it cannot load local images so I changed get_stylesheet_directory() to get_stylesheet_directory_uri() like this

         function loopImages(){
            $imagePath = get_stylesheet_directory_uri()."/IMAGES/sponsors/";
            $filesList =glob($imagePath.'*.{JPG,jpg,PNG,png}', GLOB_BRACE);
            echo $filesList;
            foreach($filesList as $file){
                echo '<img src="'.$file.'">';
            }
        }
        loopImages();

but, it shows nothing. Just nothing. What did I do wrong? How can I render my local images?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

get_stylesheet_directory was necessary for the glob function to work, you need a combination of both, e.g. fetch the files in that directory:

$imagePath = get_stylesheet_directory() . "/IMAGES/sponsors/";
$filesList = glob( $imagePath . '*.{JPG,jpg,PNG,png}', GLOB_BRACE );

and display the files at that URL:

$imagePathURL = get_stylesheet_directory_uri() . "/IMAGES/sponsors/";
...
    echo '<img src="' . esc_url( $imagePathURL . basename( $file ) ) . '">';

Notice that I wrapped it in esc_url, this is escaping and we do it to keep things secure and avoid injection attacks.

TLDR:

  • glob wants a folder path
  • but <img wants a URL instead


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment