I was developing a WordPress site for a client who required multiple images for each of the products that they offered. Instead of uploading each one through the WP uploader, I decided the best approach would be to first upload them all into a specific folder using FTP, and then use the opendir
function in PHP to retrieve them all.
For this example all of my images were added to a folder called products
in the wp-content/uploads/
directory.
First we need to figure out where the uploads folder is located. Luckily, WordPress has a function made just for that purpose.
$uploads = wp_upload_dir();
Now let’s start with the code to get all the files in the products
directory. We’re going to store them in an array.
if ($dir = opendir($uploads['basedir'].'/products')) { $images = array(); while (false !== ($file = readdir($dir))) { if ($file != "." && $file != "..") { $images[] = $file; } } closedir($dir); }
Now our $images
array contains all the images we added to the products
directory.
To display the images, all we have to do is something like this:
echo '
- ';
foreach($images as $image) {
echo '';
}
echo '
The above code will have all the images displayed in an unordered list.
Here is everything put together:
'; foreach($images as $image) { echo ''; } echo ''; ?>
Here is an alternative which removes having the need for an array:
'; if ($dir = opendir($uploads['basedir'].'/products')) { while (false !== ($file = readdir($dir))) { if ($file != "." && $file != "..") { echo ''; } } closedir($dir); } echo ''; ?>
If you’re not using WordPress, all you have to do is add the absolute file path to the opendir
function so that it looks something like this:
opendir('/home/maindir/public_html/products')