Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

Exclude Featured Image From WordPress Image Attachments Loop

Last updated on:

About Image Attachments…

One of the coolest things about WordPress is the ability to use “Image Attachment loops” to showcase all the images attached in a given post. For example on my latest premium Theme (Minim Portfolio WordPress Theme) the single portfolio pages come with several styles (slider, gallery, list, full images…) which use a custom loop that pulls in all the images attached to the post so you can easily manage a kick a*s gallery without having to use any shortcodes.

This is the a sample loop I use for pulling the image attachments on a post using the get_posts function…

//attachement loop
 $args = array(
 'orderby' => 'menu_order',
 'post_type' => 'attachment',
 'post_parent' => get_the_ID(),
 'post_mime_type' => 'image',
 'post_status' => null,
 'posts_per_page' => -1
 );
 $attachments = get_posts($args);

Excluding Featured Image From Attachment Loop

Showing all the image attachments for a post is great for usability, however, sometimes a user may want to exclude a certain image such as their featured image. Having a separate featured image might be more useful on some sites then having to choose an image that is also a part of the post’s gallery. For my Minim theme I included a handy meta option for selecting to include or exclude your featured image from the attachment loop. Although I’m not going to show you how to include the whole meta option (you can buy the theme if you really want to see that) but I will show you below how to exclude your featured image from the attachments loop.

  1. First you’ll set the featured image ID as a variable “$thumb_ID”
  2. Then we’ll add this to the exclude argument for the attachments loop. Very simple (but handy) stuff.
  3. See the code….
//get featured image ID
$thumb_ID = get_post_thumbnail_id( $post->ID );

//attachement loop - with exclude argument for featured image
$args = array(
'orderby' => 'menu_order',
'post_type' => 'attachment',
'post_parent' => get_the_ID(),
'post_mime_type' => 'image',
'post_status' => null,
'posts_per_page' => -1,
'exclude' => $thumb_ID
);
$attachments = get_posts($args);
Checkout the “Get_Posts” function at the WP codex for more info on the exclude parameter.
Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

2 Comments

  1. Maarten Kleyne

    Thanks a bunch for this simple and effective bit of code. It/you just helped me out. Cheers!

  2. Nirav Dave

    Hey AJ,

    Thank you so much for sharing this. Very helpful!

    Nirav

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.