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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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:
globwants a folder path- but
<imgwants 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