WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
Beginner's Guide for WordPress / Start your WordPress Blog in minutes
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

WPBeginner» Blog» Themes» How to Get All Post Attachments in WordPress Except for Featured Image

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

Last updated on February 6th, 2012 by Editorial Staff
52 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
How to Get All Post Attachments in WordPress Except for Featured Image

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.

52 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Properly Move Your Blog from WordPress.com to WordPress.org

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

25 Comments

Leave a Reply
  1. prabhath says:
    Jun 10, 2016 at 2:45 am

    Hi
    i try below code to get post attached image.
    but always I update image it’s only same images shows.
    please advice anyone.

    function sunset_get_attachment(){
    	$output = "";
    	if( has_post_thumbnail() ): 
    			$output = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
    		else:	
    			if($attachment):
    				foreach($attachments as $attachment):
    					$output = wp_get_attachment_url( $attachment-&gt;ID);
    					
    				endforeach;
    			endif;
    			wp_reset_postdata();
    		endif;
    
    	$attachments = get_posts(array(
    		'post_type'=> 'attachment',
    		'posts_per_page' => -1,
    		'post_parent' => get_the_ID()
    		));
    	return $output;
    }
    
    Reply
  2. Patel Yatin says:
    Oct 21, 2015 at 5:31 am

    ‘attachment’
    );

    $attachments = get_posts($args);
    if ($attachments)
    {
    foreach ($attachments as $attachment)
    {
    echo wp_get_attachment_image($attachment->ID, ‘full’);
    }
    }

    endwhile;
    endif;
    ?>

    Reply
  3. Akshay says:
    Jun 13, 2015 at 4:47 pm

    Hi,

    I’ve been able to pull all images that I needed using your code and display them on a custom page. Can you please tell me how can I get these images to work like a gallery/slider?

    Cheers,
    Akshay

    Reply
  4. Ramesh says:
    Mar 31, 2015 at 7:47 am

    How to add restricon to it? Means if author already added gallery then I don’t want to show it on that post. Can we do this? Please Reply

    Reply
  5. helloo says:
    Oct 30, 2014 at 10:30 pm

    I know this article is old, but thanks so much for this! I’ve been trying to figure out how to do this for a while now, for my theme that no longer has support.

    Reply
  6. Neha Jalan says:
    Sep 4, 2014 at 8:14 am

    but where should i write this code??

    Reply
  7. Weblizar says:
    May 24, 2014 at 1:47 pm

    I really thanks to you posting this useful code spinet. Too helpful for making a custom plugin code.

    Thanks so much
    Weblizar

    Reply
  8. Nazakat Ali says:
    May 23, 2014 at 12:41 am

    This is nice tutorial. I want to get image url instead of image attachment page as a image link

    Reply
  9. moreirapontocom says:
    Apr 28, 2014 at 11:09 pm

    Great post! Thanks for sharing!!

    Reply
  10. Angel says:
    Aug 3, 2013 at 7:06 am

    I’ve inserted this code, but when I use it the page is blank. I’ve changed the custom post type name to match my own custom post type but still nothing shows.

    Here’s the code:

    post_type == ‘gallery’ && $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 ” . $thumbimg . ”;
    }

    }
    }
    ?>

    Any help would be appreciated.

    Reply
    • Angel says:
      Aug 3, 2013 at 7:07 am

      sorry I accidentally clipped the code:

      post_type == ‘gallery’ && $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 ” . $thumbimg . ”;
      }

      }
      }
      ?>

      Reply
  11. Toure says:
    May 5, 2013 at 9:50 pm

    I tried the code about and could not get the attachment for a cpt
    I defined the cpt type by this query first:

        <?php $query = new WP_Query( array( 'post_type' => 'news', 'paged' => $paged ));
    		if ( $query->have_posts() ) : ?>
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
    <?php
    if ( $post->post_type == 'people' && $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>';
    			}
    			
    		}
    	}
    ?>
          <?php endwhile;?>
          <?php endif; ?>
    
    
    Reply
  12. Sankalp says:
    Sep 24, 2012 at 10:39 am

    how can i display full image in attachment not its thumbnail

    Reply
    • Editorial Staff says:
      Sep 24, 2012 at 11:04 am

      Look in line 12 of the code where it says thumbnail-size. That’s really the image size. You can use one of the pre-existing sizes to show the image. The value “full” there would do the job.

      Reply
  13. phillip says:
    Jun 19, 2012 at 5:24 am

    problem:
    1. insert a image into a post and press save
    2. reload page with your code inside the loop, it works great
    3. now remove the image from the post and save
    4. reload and the image still there!!!!
    This ins’t correct and I can’t find a solution for this on the internet

    Thanks

    Reply
    • Editorial Staff says:
      Jun 19, 2012 at 6:10 am

      Are you removing the image from the post? or are you deleting the image altogether? Because if you just remove the image code from the post content, then it will not go away. The image stays attached to the post it was uploaded too unless you DELETE it.

      Reply
      • Phillip says:
        Jun 19, 2012 at 9:10 am

        That’s what I figured it out.
        Doesn’t make sense to me.

        If you want to remove an image from a post and keep it for later use, the attachment will continue to appear using your code. I have to delete it!?

        If instead of removing you just want to reuse the image in a second post, that second post will not show the image as attachment because there’s only one field for parent reference – parent_id – can’t point to 2 different IDs. I have to upload a second file equal to first one!?

        This are very simples tasks that don’t work out of the box. Why is wordpress working like this? I believe that must be a very strong reason for that…

        Reply
        • clivio says:
          Jan 18, 2016 at 10:02 am

          I’ve got the same problem. When you want to reuse image in another post i doesn’t work.

  14. Pete says:
    Jun 16, 2012 at 4:38 am

    Doesn’t seem to work for me?

    Reply
    • Pete says:
      Jun 16, 2012 at 4:40 am

      Got it working, I deleted this part…
      ‘$post->post_type == ‘data-design’ && ‘

      Reply
      • Editorial Staff says:
        Jun 16, 2012 at 9:46 am

        Glad you were able to get it to work.

        Reply
        • Pete says:
          Jun 25, 2012 at 7:18 am

          I think you should rename the post … “How to Get All Post Attachments in WordPress Except for Featured Image from a custom post type” as others like myself might see it as pertaining to all/any posts (which it doesn’t)… just might help (especially with search results) :)

        • Editorial Staff says:
          Jun 25, 2012 at 8:21 am

          You can easily do what you did above, and it works.

  15. shankarsoma says:
    Feb 8, 2012 at 5:51 am

    Dear Webmaster

    You have not mentioned where to add codes in WordPress files is it functions.php, post.php or other things

    Do please elaborate the same

    Reply
    • wpbeginner says:
      Feb 8, 2012 at 8:01 am

      @shankarsoma You have to paste it inside the loop. Most of the time, you will create a custom page and post it in the loop. In our case, we created a custom post type and ran it in that loop. So it is very subjective which file it will go in … It all depends on how you use it.

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
TrustPulse
TrustPulse
Instantly get 15% more conversions with social proof. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2021 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2021)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2021)
    • SiteGround Reviews from 4464 Users & Our Experts (2021)
    • Bluehost Review from Real Users + Performance Stats (2021)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2021 – Step by Step Guide
Deals & Coupons (view all)
AccessPress Themes
AccessPress Themes Coupon
Get 15% off on AccessPress Themes collection of premium WordPress themes and plugins.
Beaver Builder Coupon Code
Beaver Builder Coupon
Get the best possible price on this easy drag-and-drop page builder plugin. From just $99 in 2020.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).

Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
  • Growth Fund
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon
  • AIOSEO

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress Security by Sucuri.