How to Get All Post Attachments in WordPress Except for Featured Image

119

Recently while working on a custom project for a client, we had to get all post attachments from a custom post type and display them at one place. Because we were creating a grid display, we had each post’s featured image serving the purpose of a separator. This is why when getting all post attachments, we needed to exclude the featured image, so it doesn’t show up twice. In this article, we will show you how to get all post attachments in WordPress except for the featured image.

All you have to do is paste the following code inside a loop.

  <?php if ( $post->post_type == 'data-design' && $post->post_status == 'publish' ) {  		$attachments = get_posts( array(  			'post_type' => 'attachment',  			'posts_per_page' => -1,  			'post_parent' => $post->ID,  			'exclude'     => get_post_thumbnail_id()  		) );    		if ( $attachments ) {  			foreach ( $attachments as $attachment ) {  				$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );  				$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );  				echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';  			}  			  		}  	}  ?>  

The code above first checks if the post type is data-design and the post status is published. You may not need the first conditional depending on what you are trying to do. Then we simply run the get_posts query. Everything is pretty self explanatory there. The key that we must highlight is the exclude feature. That line is making sure that featured image does not show up. If you take that line away, then the featured image will show up. After specifying all the parameters, we simply specify what to do when each attachment is pulled. We are pulling attachment type for the class variable. Then the $thumbimg variable is simply using wp_get_attachment_link to pull the image at a specific thumbnail size, and it also hyperlinks the image to the single attachment pages. In the final step, we simply echo it.

We ran this code inside a loop with a separate call for featured image which links to the individual post. Final outcome looked something like this:

Attachment Grid

Each featured image served as an album identifying image which you can see. The grey spots were filled with the attachments for the post. We hope that this would help those who are looking to push WordPress beyond a blogging platform.