<?php
/* settings */
$image_dir = 'gallery/';
$per_column = 3;
$count=0;
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
if(strstr($file,'-thumb'))
{
$files[] = $file;
}
}
}
closedir($handle);
}
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<a class="thumbnail" rel="one-big-group" href="',$image_dir,str_replace('-thumb','',$file),'"><img src="',$image_dir,$file,'" width="100" height="100" /></a>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo '<p>There are no images in this gallery.</p>';
}
?>
How can I add captions to each of the images?
Thank you very much for the answer!
Your code is traversing the files within the specified directory looking for files containing
...-thumb...in the filename, appending them to an array, and then looping over the array to generate HTML for displaying the thumbnail image gallery.Adding additional information to something like this, given the very limited code you’ve provided, can be done in any number of ways
related column containing captions/descriptions. This might be more
trouble than it’s worth depending on what you’re trying to achieve.
You could use a flat file which you could parse line by line (instead of traversing the
folder for
...-thumb...images), containing some format likeYou could includ a small caption in the filename itself, and parse/format the caption from the filenames. This would probably be the quickest route, but most limiting in terms of flexibility in the length/characters allowed for the captions.
To actually add the caption to the generated HTML, you can use a
titleattribute as @rockerest suggested, however I’d personally add such a caption to to the image itself, as that is what the caption is describing (not the link)UPDATE
To answer your comment (this provides better formatting for code), Let’s say we have a file with name
file1-thumb--some_description_here.jpg, you can parse and format the caption with preg_replace$captionis now some description here