Over the past couple of weeks I’ve been working on a number of WordPress projects, all of which have needed some basic photo gallery functionality. As I’ve mentioned before in previous posts, NextGEN gallery is my WordPress gallery of choice, there really is nothing that comes close to it in terms of features and customisation (that I know of, if there are others post a comment!).
To add a gallery (or album) to a post / page is as simple as adding ‘[ nggallery id=x ]‘ to the post content… super! One issue though… what happens when you allow a client to edit and add new pages; well what usually happens is the tag gets deleted or changed, the gallery breaks, client panics and the virtual world ends (well not quite, but close). A technique I have been using to help solve this issue involves using WordPress custom fields and the excellent Get custom field values plug-in. You can grab the custom field values directly from WordPress using get_post_meta() but the plug-in makes it much easier.
Digging through the nggfunctions.php file in the NextGEN gallery plug-in folder reveals a whole host of useful functions that can be easily called directly from inside your WordPress theme. So say you wanted a gallery in a post page, but didn’t want the client to have to remember ‘[ nggallery id=x ]‘ every time, simply add this code next to your content in the single.php file:
1 2 3 4 5 6 <?php if(c2c_get_current_custom('galleryID') != ''): $gID = c2c_get_current_custom('galleryID'); echo nggShowGallery($gID); endif; ?>
Add a custom field of galleryID with an integer value linking to the relevant gallery and you’re done. Now the client can pick out the galleryID custom field from a drop-down since WordPress remembers the custom fields used. Much easier for a client to remember than adding the tag every time.
I highly recommend looking through the nggfunctions.php file, here are just a few functions that are available:
- nggShowAlbum(): Show a whole album depending on the ID.
- nggSinglePicture(): Show a single picture from an ID.
- nggShowRandomRecent(): Show random image(s) from a certain gallery.
- nggShowSlideshow(): Show a flash slideshow pulling images from a specified gallery.
I have used nggShowRandomRecent() quite a few times in the past few months, here’s a quick example:
1 2 3 4 5 <?php //Show 6 random images using 'my-template' from gallery 4 //(order, number of images, template, gallery ID) echo nggShowRandomRecent('random', 6, 'my-template', 4); ?>
Pick 6 images at random from a selected gallery on page load, very simple and effective.
Note: When using the random images function make sure you don’t have any WordPress caching plug-ins running on the selected page, else it won’t work as the page gets cached on first load. It took me a good 15 minutes to figure out why the function had suddenly stopped working due to this slight oversight.