Get all the images from custom post type in WordPress

I am working on a portfolio WordPress theme and trying to grab and display every image in portfolio-single page.

I am using following code but its not working.

Read More
<div class="thumb">
   <?php 
   $args = array(
       'post_type' => 'attachment',
       'numberposts' => -1,
       'post_status' => 'any',
       'post_mime_type' => 'image',
       'post_parent' => $post->ID
   );

   $attachments = get_posts($args);
   if($attachments) : ?>
       <ul class="portfolio-image-list">
           <?php foreach ($attachments as $attachment) : ?>
           <li class="box">
               <figure>
                  <?php the_attachment_link($attachment->ID, true); ?>
               </figure>
            </li>
            <?php endforeach; ?>
        </ul>
   <?php else: ?>
        <div class="box">
           <p>No images found for this post.</p>
       </div>
    <?php endif; ?>

</div>

Please help.

Related posts

1 comment

  1. You’re trying to retrieve a list of the posts rather than the attachments to the specific post in question. You’d instead need to retrieve the child objects of type ‘attachment’:

    $args = array(
      'post_type' => 'attachment',
      'posts_per_page' => -1,
      'post_status' => 'any',
      'post_mime_type' => 'image',
      'post_parent' => $post->ID
    );
    
    $attachments = get_children( $args );
    

    But you can now use the ‘get_attached_media’ function to make this even easier. Try replacing the $attachments line with:

    $attachments = get_attached_media( 'image', $post->ID );
    

    If that still doesn’t work, you can temporarily add die($post->ID); in your template and make sure that it’s outputting the post ID correctly. If not, make sure you’re running the code within The Loop so that $post->ID is available.

Comments are closed.