views:

34

answers:

1

I'm creating a wordpress meta box and I need to scan a directory of subdirectories containing images within my template and add these to a select dropdown so I can use the filename in my template.

The images are currently arranged in the folder like this:

Parent Folder
|_ Secondary Folder
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif
|_ Secondary Folder
   |_ Image.png
   |_ Image.jpg
   |_ Image.gif

Ideally I'd like to keep that structure in my select dropdown ie.

Secondary Folder .
   |_ Image.png

I've been using this:

function get_dir_path(){
    return dirname(__FILE__).'/library/images';
}
$largeImagesdir = get_dir_path() . '/960x345/';


    if ($dh = opendir($largeImagesdir)) {
        while (($file = readdir($dh)) !== false) {
            $lfiles .= '<option>' . $file . '</option>';
        }
        closedir($dh);
    }

    $buildbox .= '<select>' . $lfiles . '</select>';

However this of course only works if I set the $largeImagesdir var to be one of the sub directories...

Can anyone help?

A: 

You need a loop inside a loop. Assuming only 2 levels of directories, in your while check if $file is a subdirectory with is_dir(), and if yes do a readdir() on that too to get its options built.

Then, you can distinguish the subdirectories by optgroup in your <select> element.

If you need multiple varying levels of subdirectories you'll need a recursive function to take care of it. The one shown here is a good starting point.

Fanis
If its more then a single level, might as well code for the general case and make it recursive.
Chris
@Chris, absolutely, I'm just trying to have Kim ease into the problem with the specific use case first. I've provided the link with ready code for the general case when she feels ready to tackle that.
Fanis
Thanks guys, yeah, I'll try the easiest method first and then take a look at the general case, too :)
Kim