0

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?

1 Answer 1

0

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
2
  • Thank you for answer, I did esc_url as you said but the url of the image is really strange. after sponsors/, comes C:Users blah blah.. and of course I get 404 error..
    – game lover
    Commented May 20, 2021 at 14:49
  • ok, solved it by using basename($file) in esc_url. Thank you for help
    – game lover
    Commented May 20, 2021 at 14:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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