Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggreagtion Enquires Welcome

Return all Images (Except the Featured Image) Attached to a WordPress Post or Page

This function supports a number of our image gallery functions. The first is published on this page. There's also an article on our blog, "Find all Images (Except the Featured Image) Attached to a WordPress Post or Page", that discuses the WordPress functions in a little more depth.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
    Return all Images (Except the Featured Image) Attached to a WordPress Post or Page
4
    http://www.beliefmedia.com/wordpress-post-images
5
*/
6
 
7
 
8
9
 
10
  $attachments = get_posts( array(
11
    'post_type' => 'attachment',
12
    'posts_per_page' => -1,
13
    'post_status' => 'any',
14
    'post_parent' => $id,
15
    'exclude' => get_post_thumbnail_id())
16
  );
17
 
18
  /* Return array of all images */
19
  if ($attachments) {
20
    $i = 0; foreach ($attachments as $attachment) {
21
      $imagesrc = wp_get_attachment_image_src($attachment->ID, $size = 'medium');
22
      $imagesrc_medium_large = wp_get_attachment_image_src($attachment->ID, $size = 'medium_large');
23
      $imagesrc_full = wp_get_attachment_image_src($attachment->ID, $size = 'full');
24
      $imagesrc_thumbnail = wp_get_attachment_image_src($attachment->ID, $size = 'thumbnail');
25
 
26
      $images["$i"]['src'] = $imagesrc['0'];
27
      $images["$i"]['medium_large'] = $imagesrc_medium_large['0'];
28
      $images["$i"]['full'] = $imagesrc_full['0'];
29
      $images["$i"]['thumbnail'] = $imagesrc_thumbnail['0'];
30
      $images["$i"]['title'] = get_the_title($attachment->ID);
31
      $images["$i"]['caption'] = $attachment->post_excerpt;
32
      $i++;
33
    }
34
  }
35
 
36
 return $images;
37
}

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment