A more elegant solution to captioning images for galleries and portfolios, and one that requires considerably less work than adding a URL variable, is to create a dependency on an accurate, descriptive image filename. In essence, this is a variation on the self-made pages technique I have demonstrated before.

Of course, your gallery images should already have descriptive filenames, with hyphens in place of spaces. Assuming that you have used a GET variable that contains the image filename (I’m going to call the variable $img for the purposes of this example), it should not be a stretch to add something like the following:

<?php $title = ucwords(sub_str(str_repace("-"," ",$image), 0, -4));
# the sub_str assumes that the file extension is always three characters

And the code for displaying the image would change to:

<img src="assets/images/<?=$image?>" alt="<?=$title?>">

While considerably more efficient that using GET, this method still has some disadvantages. The primary drawback is that the caption is limited to whatever the image filename is… and because filenames cannot contain commas or other punctuation, nor be longer than 255 characters, neither can the caption.

While rather more complex, a technique that avoids those disadvantages entirely is one that uses metadata from the image itself to create the caption.