WordPress has a simple gallery function built in, it provides a straight forward way to add a gallery of images into your post or page with an auto generated shortcode. It works great for displaying a gallery in one of your posts or pages, but there is one tweak that a lot of people seem to ask about; how do keep my featured image from being displayed as a gallery item?
Before we dive into removing the featured image from your gallery let’s go over how to create a gallery within a WordPress post or page (if you are familiar with this skip to the next part).
Adding a gallery of images is a really easy process in WordPress. Want to see a live example? Check out our iPhone 5 review post, we create a gallery that has 6 images being displayed in 2 rows and 3 columns.
To create a WordPress gallery that can be displayed in either a post or page follow these three steps:
Your gallery is now complete, the shortcode WordPress generated should similar to this:
[<span>gallery link="file" columns="2" orderby="rand"</span>]
The WordPress Gallery doesn’t allow you to automatically exclude the featured image from displaying. Many theme’s display a featured image in your loop; and having the same featured image appear in multiple places can be repetitive. To build image galleries that exclude your featured image, you’ll need to add some new code to your functions.php file (if you’re using a standard WordPress theme you will want to create a child theme first).
Add the following code to your functions.php file. You can access it via ftp: **yoursite**/themes/**yourthemename**/functions.php
function exclude_thumbnail_from_gallery($null, $attr) { if (!$thumbnail_ID = get_post_thumbnail_id()) return $null; // no point carrying on if no thumbnail ID // temporarily remove the filter, otherwise endless loop! remove_filter('post_gallery', 'exclude_thumbnail_from_gallery'); // pop in our excluded thumbnail if (!isset($attr['exclude']) || empty($attr['exclude'])) $attr['exclude'] = array($thumbnail_ID); elseif (is_array($attr['exclude'])) $attr['exclude'][] = $thumbnail_ID; // now manually invoke the shortcode handler $gallery = gallery_shortcode($attr); // add the filter back add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2); // return output to the calling instance of gallery_shortcode() return $gallery; } add_filter('post_gallery', 'exclude_thumbnail_from_gallery', 10, 2);
Credit for the following code goes to stackoverflow.com member TheDeadMedic.
Did this post help you use your your image gallery more effectively? Do you have any suggestions or better ways to automatically exclude a featured image in an image gallery? Let us know what you think, and leave us a comment.
By John Horne – December 3rd, 2012.
Sultan Solutions Tech Blog is dedicated to providing valuable IT, Tech, and Web tips and tricks. Subscribe to our feed and be sure to check back often.
Top Comments