Exclude Featured image from WordPress gallery

I needed to add the default wordpress gallery to page with a featured image but found that the featured image was also included in this gallery.

The best way I found to exclude this is to add the code below to your site

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);

I found this solution here: http://stackoverflow.com/a/4347635. Its an old post but still works.

2 Comments

Leave a Comment