WordPress handles images very well and there simply isn’t much it can’t do. However, multiple galleries (via post ID’s) on the same page, uploading multiple images and formatting can all occasionally become either problematic or a chore. Simply put, I’ve found that it takes too much time to create the large galleries that I’m often required to post. Sure, there are lots of excellent plugins that perform some pretty awesome white-man-magic, but they’re usually offering a little more than what I need and fall shy of what I want. The solution? I wrote a quick shortcode function that’ll scan the contents of a defined directory and resize the contents for inclusion in a thumbnail gallery (using timthumb.php). The thumbnail will link to the larger (but scaled) version of the same image. I’ve had at least one request for this kind of functionality in the past.
First, an example. The shortcode of [ttgallery name="branson" galleryname="This is an Image Gallery Title"] will render the following gallery.
This is an Image Gallery Title | |||
Available shortcode attributes are as follows:
name – The name attribute is the name of the directory that contains all your gallery images.
galleryname – This is the title of the gallery that will display under the gallery.
link – “true” if you wish to link each image to the larger version. True by default.
linkwidth – This is the scaled width of the image you link to.
cols – This is the number of columns that displays your thumbnail images. For example, if set to cols=”4″, the gallery will be four images wide.
row – You can define the width of individual table cells with row.
tablewidth – You can choose to define the table width. If not specified, it’ll default to
cols x width(width = with of each thumbnail image and cols = number of columns).cellpadding & cellspacing – Cellpadding and cellspacing add a ‘gap’ in your gallery. By default, cellpadding will default to 5 (meaning that your thumbnail images won’t touch each other).
All the standard timthumb attributes apply with the most notable being width. This will define the width of each thumbnail. Width must be defined to ensure correct formatting.
Some common sense prevails when you create a gallery. Based on a post width of, say, 480 pixels, you might choose to display three thumbnails wide with a width of 150px. Example: [ttgallery name="directoryname" width="150"].
The shortcode of [ttgallery name="virginaustraliademo" cols="2" width="200" galleryname="Virgin Australia Game Change Program"] will render as follows. Each image ‘title‘ tag is defined by the actual name of the image. Using something like WP Fancy Zoom, it means that the image name will be rendered underneath the image (try it with the gallery above). Underscores, hyphens and file extensions will be replaced by a space. The first character of each word will also be changed to UPPER-case text. So, as an example, the image name of holiday-in_America.jpg will display (as a title) as ‘Holiday In America‘.
Virgin Australia Game Change Program | |
Setup
You will need to define three lines in the shortcode function:
First, you’re requried to define the full web path to timthumb.php.
$timthumb = "http://www.Domain.com/timthumb/timthumb.php";
Second, you’re required to set up the web path to a directory that’ll store all your galleries. A sensible place to put it would be under your root images directory. Every subsequent gallery will be created underneath the gallery directory. Note that there is no trailing slash.
$ImageDirectory = "http://www.Domain.com/images/gallery";
Third, you must add the full path to your gallery directory. This is so PHP’s glob() function can scan the directory for all images. Again, note that there is no trailing slash. If you don’t know what the full path to your newly created gallery directory is, you can use the getcwd(); function to find out (a file is included in the code below… simply upload and view the output in your browser).
$ImagePath = "/home/public/www/images/gallery";
Two Galleries in the Gallery Directory
The Shortcode
You should download the code below and copy it into your theme’s functions.php file or custom functions plugin.
// TimThumb Gallery
function internoeticsGallery($atts) {
extract(shortcode_atts(array(
'name' => '',
'galleryname' => '',
'link' => 'true',
'linkwidth' => '600',
'cols' => '4',
'row' => '4',
'tablewidth' => '',
'border' => '0',
'cellpadding' => '0',
'cellspacing' => '5',
// Timthumb Attributes
'width' => '100',
'height' => '',
'crop' => '',
'filter' => '',
'sharpen' => '',
'zoom' => '',
'quality' => '70'
), $atts));
// *******************************************
// You MUST define the following as per your own configuration
// Path to Timthumb
$timthumb = "http://www.YourDomain.com/timthumb/timthumb.php";
// The Location of your GALLERY directory (no trailing slash)
$ImageDirectory = "http://www.YourDomain.com/images/gallery";
// Full path to Image directory (no trailing slash)
$ImagePath = "/home/something/public/www/images/gallery";
// *******************************************
$directory = "$name";
$images = glob("$ImagePath/$directory/*.{jpg,png,gif}", GLOB_BRACE);
$count = count($images);
if ($tablewidth == "") $tablewidth = $cols * $width;
if($count == 0) { echo "No images or path error"; }
else {
$gallery .= '<center><table width="'.$tablewidth.'" border="'.$border.'" cellpadding="'.$cellpadding.'" cellspacing="'.$cellspacing.'">';
$gallery .= '<tr>';
for($i=0;$i<=$count;$i=$i+1) {
foreach($images as $image) {
// Prettify the image name for title/alt tags
$remove = array("-", "_", ".png", ".jpg", ".gif", ".jpeg");
$imageName = str_replace($remove, " ", basename($image));
$imageName = ucwords($imageName);
$gimage = ''.$timthumb.'?src='.$ImageDirectory.'/'.$directory.'/'.basename($image).'';
$limage = ''.$timthumb.'?src='.$ImageDirectory.'/'.$directory.'/'.basename($image).'';
if($width) $gimage .= '&w=' . $width;
if($linkwidth) $limage .= '&w=' . $linkwidth;
if($height) $gimage .= '&h=' . $height;
if($crop) $gimage .= '&a=' . $crop;
if($filter) $gimage .= '&f=' . $filter;
if($sharpen) $gimage .= '&s=' . $sharpen;
if($zoom) $gimage .= '&zc=' . $zoom;
if($quality) $gimage .= '&q=' . $quality;
if($linkwidth) $limage .= '&q=' . $quality;
$i++;
if($i%$cols==0) {
$gallery .= '<td width="'.$row.'" align="'.$align.'">';
if ($link != "false") $gallery .= '<a href="'.$limage.'" title="'.$imageName.'">';
$gallery .= '<img src="'.$gimage.'" alt="'.$imageName.'" title="'.$imageName.'" border="0" />';
if ($link != "false") $gallery .= '</a>';
$gallery .= '</td></tr><tr>';
} else {
$gallery .= '<td width="'.$row.'" align="'.$align.'">';
if ($link != "false") $gallery .= '<a href="'.$limage.'" title="'.$imageName.'">';
$gallery .= '<img src="'.$gimage.'" alt="'.$imageName.'" title="'.$imageName.'" border="0" />';
if ($link != "false") $gallery .= '</a>';
$gallery .= '</td>';
}
}
$gallery .= "</tr>";
if ($galleryname != "") $gallery .= "<tr><td colspan=\"$cols\"><pre><small>$galleryname</small></pre></td></tr></table></center><br>";
else $gallery .= "</table></center>";
}
}
return $gallery;
}
add_shortcode("ttgallery", "internoeticsGallery");
PHP Code
If you’re after a PHP function that will do as I’ve described above for use outside of WordPress, something like this will get you started. You’ll need to define the first few lines as above.
function igallery($galleryname,$cols) {
// Define the following lines
$ImageDirectory = "http://www.YourDomain.com/images/gallery/";
$ImagePath = "/home/something/public/www/images/gallery";
$images = glob("$ImagePath/$galleryname/*.{jpg,png,gif}", GLOB_BRACE);
$count = count($images);
if($count == 0) { echo "No images or path error"; }
else {
echo '<table border="0" cellpadding="3" cellspacing="0">';
echo '<tr>';
for($i=0;$i<=$count;$i=$i+1) {
foreach($images as $image) {
$i++;
if($i%$cols==0) {
echo '<td width="100" align="center"><img src="'.$ImageDirectory.'/'.$galleryname.'/'.basename($image).'" border="0" /></a></td></tr><tr>';
} else {
echo '<td width="100" align="center"><img src="'.$ImageDirectory.'/'.$galleryname.'/'.basename($image).'" border="0" /></a></td>';
}
}
echo "</tr></table><br>";
}
}
}
Usage:
echo igallery(myholiday,4);
Not caching the images is inefficient. PHP supports resizing images and caching but it’s outside the scope of this little post. Another time!
The code is a little messy so make sure you come back to check for updates. If you have any problems, please let me know.
|
|
Download: WordPress Image Gallery Shortcode |
If you liked this article, you may also like:


Nice work, Marty. But I’m sorry to inform you that it simply outputs your code to the page, it does not render to a gallery. The ttgallery shortcode is not recognized. What do you think may be the problem?
I am using WordPress 3.4.2 and I inserted this code into my theme’s functions.php (where all other shortcodes are).
Thanks in anticipation of your quick response.
You mean it outputs [ttgallery] onto your page? This will mean that WP simply isn’t reading the code. I’ve tested it on 3.4.2 and it works fine (in fact, I installed it on a new site yesterday).
Did you have timthumb.php installed and working before you tried the above?
It’s really hard for me to know what the problem is when I don’t have access to what you’ve done. If you trust me, send me either your functions.php file or give me FTP access and I’ll have a look.
Hi Marty,
I’ve been reading through your tutorials all night and just cant seem to get timthumb to work properly. My gallery gets populated by box with a cross inside it, along with the image name. I’d be so grateful if you could take a look for me.
If you have the time I’d be more than happy to give you FTP access?
Hi Jeroen. First, have you checked timthumb is working properly without the gallery function? If it’s still not working, I’m more than happy to help. Send me an email to marty [at] internoetics {dot} com.
It can be confusing…
For the interest of others, Jeroen’s problem above was caused by a few things. First, his server doesn’t allow World (777) permissions. 755 worked fine. Also, memory allocation for larger issues was causing problems, so, in the end, we just made all his images smaller (600 pixels, since this is the largest he’ll display anyhow). It’s working now and looking great (http://jeroenandsarah.com).