RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

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

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

I recently had the need to return all images that were imported into a WordPress post or page (except the featured image). Since my specific use will likely be of no use to you, I've reproduced some generic examples here of how the feature might be used.

You can find an example of how this function might be used to created an image gallery here ("Create an Image Grid Gallery With WordPress Shortcode").

Return an Array of Attached Images to a Post

The following function will return an array of all image URLs (except the featured image) attached to a post. The post ID can be the current post, or any other.

1
<?php 
2
/*
3
 Find all Images (Except the Featured Image) Attached to a WordPress Post or Page
4
 http://www.beliefmedia.com/wordpress-post-images
5
*/
6
 
7
function beliefmedia_wordpress_get_images($id, $size = 'large') {
8
 
9
  global $post;
10
  $postid = ($id == $post->ID) ? $post->ID : $id;
11
 
12
  $attachments = get_posts( array(
13
    'post_type' => 'attachment',
14
    'posts_per_page' => -1,
15
    'post_status' => 'any',
16
    'post_parent' => $postid,
17
    'exclude' => get_post_thumbnail_id())
18
  );
19
 
20
  /* Return array of all images */
21
  if ($attachments) {
22
    foreach ($attachments as $attachment) {
23
      $imagesrc = wp_get_attachment_image_src($attachment->ID, $size);
24
      $images[] = $imagesrc['0'];
25
    }
26
  }
27
 return $images;
28
}

An Example Shortcode Function

The following shortcode function is pretty basic and is unlikely to serve any noble purpose. It'll simply render all the attached images (from any post) on your page.

1
<?php 
2
/*
3
 Find 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
  extract(shortcode_atts(array(
9
    'id' => '',
10
    'size' => 'large'
11
  ), $atts));
12
 
13
  global $post;
14
  if ($id == '') $id = $post->ID;
15
  $attachments = internoetics_wordpress_get_images($id, $size);
16
 
17
  if ($attachments) {
18
    foreach ($attachments as $attachment) {
19
      $source .= $attachment . '<br>';
20
    }
21
   }
22
 return '<p>' . $source . '</p>';
23
}
24
add_shortcode('bmimagestest','beliefmedia_wordpress_get_images_except_featured');

For the purpose of providing an example, I've uploaded 5 Apollo 11 photographs. I've used the shortcode of [postimagestest]. To return images attached to a different post, use [postimagestest id="1234"] (where 1234 is your post ID). The result:

For the purpose of formatting the URL (so it doesn't line wrap), I've used the beliefmedia_split_string() function from here. I could have used WP's url_shorten() function, but it only removes the http://www component and truncates to 35 characters with trailing dots -- meaning all URLs would look the same. Our method preserves the filename.

Post Images (Except Features Image) in Tower

The next sample function isn't anything you would likely use. It will render all your post images (except the featured image) into your WordPress post or page with shortcode.

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
 Find 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
  extract(shortcode_atts(array(
9
    'url' => false,
10
    'link' => 1,
11
    'truncate' => 1,
12
    'parent' => false
13
  ), $atts));
14
 
15
  global $post;
16
  $parent = ($parent === false) ? $post->ID : $parent;
17
  if ($url == 0) $truncate = 0;
18
 
19
  $attachments = get_posts( array(
20
    'post_type' => 'attachment',
21
    'posts_per_page' => -1,
22
    'post_status' => 'any',
23
    'post_parent' => $parent,
24
    'exclude' => get_post_thumbnail_id())
25
  );
26
 
27
  if ($attachments) {
28
    foreach ($attachments as $attachment) {
29
 
30
      // $imgurl = ($url) ? wp_get_attachment_image_src($attachment->ID, 'full') : wp_get_attachment_image($attachment->ID, 'large');
31
      $imgurl = ($url) ? wp_get_attachment_image_src($attachment->ID, 'full') : wp_get_attachment_image_src($attachment->ID, 'thumbnail');
32
      $textlink = $imgurl['0'];
33
 
34
      if ( (strlen($textlink) > 58) && ($truncate) && ($url)) {
35
        $textlink = substr($textlink, 0, 35) . '...' . substr($textlink, -20);
36
      }
37
 
38
      $imglink = ($link) ? '<a href=&quot;' . $imgurl['0'] . '&quot;>' . $textlink . '</a>' : $textlink;
39
      $source .= ($url) ? '<li>' . $imglink . '</li>' : '<div style=&quot;text-align: center; padding: 10px;&quot;><img src=&quot;' . $imgurl['0'] . '&quot;></div>';
40
    }
41
   }
42
 
43
 return ($url !== false) ? '<ul>' . $source . '</ul>' : $source;
44
}
45
add_shortcode('bmpostimages','beliefmedia_wp_get_images_except_featured');

If you require shortcode to work in a sidebar widget, you'll have to enable the functionality with a filter. If you're using our custom functions plugin, you'll have that feature enabled by default.

The short snippet is the basis for creating a gallery. Of course, you would select or create an appropriate image size and then align them in paginated responsive rows. We're just outputting the thumbnail image (automatically created when uploaded) and we're stacking them in a tower. The shortcode: [bmpostimages] wil return the following:

To return the images associated with another post, use [bmpostimages parent="12345"] where 12345 is the post ID of the other post. To display a list rather than images, use [bmpostimages url="1"]. The result of the list returns the following:

Again, it's not a real-world example, just a proof that you can use to build your own stuff.

The Image Gallery Function

We'll send people back to the following function from time-to-time. It's most often used in various image gallery features we share.

1
<?php 
2
/*
3
 Find 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
  $attachments = get_posts( array(
10
    'post_type' => 'attachment',
11
    'posts_per_page' => -1,
12
    'post_status' => 'any',
13
    'post_parent' => $id,
14
    'exclude' => get_post_thumbnail_id())
15
  );
16
 
17
  /* Return array of all images */
18
  if ($attachments) {
19
    $i = 0; foreach ($attachments as $attachment) {
20
      $imagesrc = wp_get_attachment_image_src($attachment->ID, $size = 'medium');
21
      $imagesrc_medium_large = wp_get_attachment_image_src($attachment->ID, $size = 'medium_large');
22
      $imagesrc_full = wp_get_attachment_image_src($attachment->ID, $size = 'full');
23
      $imagesrc_thumbnail = wp_get_attachment_image_src($attachment->ID, $size = 'thumbnail');
24
 
25
      $images[&quot;$i&quot;]['src'] = $imagesrc['0'];
26
      $images[&quot;$i&quot;]['medium_large'] = $imagesrc_medium_large['0'];
27
      $images[&quot;$i&quot;]['full'] = $imagesrc_full['0'];
28
      $images[&quot;$i&quot;]['thumbnail'] = $imagesrc_thumbnail['0'];
29
      $images[&quot;$i&quot;]['title'] = get_the_title($attachment->ID);
30
      $images[&quot;$i&quot;]['caption'] = $attachment->post_excerpt;
31
      $i++;
32
    }
33
  }
34
 
35
 return $images;
36
}

Considerations

  • You can get the image title (since you have the ID) with the code of $attachmenttitle = get_the_title($id);. This might come in handy if you were creating an image "index". In fact, you could loop through all your published posts and generate a paginated index with nice scaled thumbnails. If the image had a title, you could display it and use it as an alt tag.
  • Need to search for all PDF documents attached to a page? Use 'post_mime_type' => 'application/pdf' in your query. This should work for any file type you can upload through WP's media library.
  • If you wanted to print a summary of images attached to a post in a page index or similar (something I'll be doing in an upcoming project) you might consider getting image meta data with the following function (or similar):
1
<?php 
2
/*
3
 Find 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
  $attachment = get_post($id);
9
 
10
  return array(
11
    'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
12
    'caption' => $attachment->post_excerpt,
13
    'description' => $attachment->post_content,
14
    'href' => get_permalink( $attachment->ID ),
15
    'src' => $attachment->guid,
16
    'title' => $attachment->post_title
17
  );
18
}

If you wanted to test the function, use the following shortcode function so you know what kind of data the function returns:

1
<?php 
2
/*
3
 Find 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
  extract(shortcode_atts(array(
9
    'id' => ''
10
  ), $atts));
11
 
12
  /* Must supply attachment ID */
13
  $attachment = get_post($id);
14
 
15
    $data = array(
16
      'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
17
      'caption' => $attachment->post_excerpt,
18
      'description' => $attachment->post_content,
19
      'href' => get_permalink( $attachment->ID ),
20
      'src' => $attachment->guid,
21
      'title' => $attachment->post_title
22
    );
23
 
24
 return 'pre' . print_r($data, true) . '/pre';
25
}
26
add_shortcode('attachmentdatatest','beliefmedia_get_attachment_data_test');

(Close the pre tags... I've removed them for formatting).

In my case, [attachmentdatatest id="1234"] returns the following array:

1
Array
2
(
3
    [alt] => Neil Armstrong after his first steps on the moon.
4
     => Neil Armstrong after his first steps on the moon. July 21 at 02:56:15 UTC.
5
    [description] => Neil Armstrong after his first moonwalk. July 21 at 02:56:15 UTC.
6
    [href] => https://www.beliefmedia.com.au/wordpress-post-images/apollo-11-01
7
    [src] => http://www.beliefmedia.com/wp-content/uploads/2017/06/apollo-11-01.jpg
8
    [title] => Neil Armstrong
9
)
  • Alternatively (to the above function, or in addition to) consider retrieving attached meta data with WP's wp_get_attachment_metadata function (particularly if you're interested in the image_meta data, that, in part, returns camera type, timestamp, and shutter speed).
  • If uploading images that aren't attached to a parent post and you would like to emulate what we've described above, you could perhaps explode a string of comma separated IDs and then loop over them individually.

Download

The download includes the shortcode and other examples on this page. If you're after something specific image related, let us know.


Title: Return all Images Attached to a WordPress Post or Page
Description: Find all Images (Except the Featured Image) Attached to a WordPress Post or Page. Includes shortcode examples.
  Download • Version 0.2, 1.4K, zip, Category: WordPress Shortcodes

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment