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.
- First you’ll set the featured image ID as a variable “$thumb_ID”
- Then we’ll add this to the exclude argument for the attachments loop. Very simple (but handy) stuff.
- 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);